Only perform JavaScript RegEx matching if it is not enclosed in [nocode][/nocode] tags

Here is the code snippet I am currently using:

var user_pattern = this.settings.tag;
user_pattern = user_pattern.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // escape regex
var pattern = new RegExp(user_pattern.replace(/%USERNAME%/i, "(\\S+)"), "ig");

The value stored in this.settings.tag is a string like "[user=%USERNAME%]" or "@%USERNAME%". This code utilizes pattern.exec(str) to identify any username within the respective tag and it functions correctly. For instance, if str = "Hello, [user=test]", then pattern.exec(str) will detect test.

Although it works properly, I want to prevent matches from occurring if the string is enclosed in [nocode][/nocode] tags. To illustrate, if

str = "[nocode]Hello, [user=test], how are you?[/nocode]"
, the pattern.exec(str) should not yield any results.

I'm uncertain about where to initiate changes. I attempted inserting (?![nocode]) before and after the pattern without success. Any assistance would be highly appreciated.

Answer №1

Before proceeding with any actions, I suggest checking if the string begins with [nocode]:

let hasNocode = /^\[nocode\]/.test('[nocode]');

If it does start with [nocode], then avoid processing it further.

Answer №2

Before attempting to locate the username(s), perhaps consider removing any instances of [nocode] first?

pattern.exec(str.replace(/\[nocode\](.*)\[\/nocode\]/g,''));

While this may not align precisely with your initial query since it involves using two distinct regular expressions, prioritizing code readability is crucial, making this method a more favorable option in that regard. I trust this solution proves beneficial 😉

Check out the JSFiddle here: http://jsfiddle.net/3ae7HYmR/2/

Derived from: Regular Expression to get a string between two strings in Javascript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Confirm the text field input to accept only alphabets, hyphens, and periods

I want to enhance the validation of my text field by restricting it to only allow letters a-z and -. Currently, if the input is invalid, a cross appears, and if it's valid, a check mark appears. However, I need the validation to also check for minimu ...

Converting HTML input to a file using JavaScript

Here is the React.js component code I'm working with: import React, {ChangeEvent, useState} from "react"; import { Button } from "@mui/material"; function UploadCVButton() { const [selectedFile, setSelectedFile] = useState(null ...

Design a personalized .OBJ / .MTL file and showcase it using the power of three.js

I attempted to create a basic blender model, export it to .obj/.mtl, and then render it with three.js. However, I am experiencing an issue. I have downloaded and uploaded the official three.js demo, and the objmtl-loader is functioning properly with the or ...

Combining multiple arrays of arrays in JavaScript

I am dealing with an array that contains nested arrays. This particular array is called template https://i.sstatic.net/QIs0Q.png template consists of 2 arrays, but the number can vary and there can be multiple levels of arrays within each one. Here' ...

Encountering CORS problems when sending a request containing JSON data in the body

I have a local react application running on port 3000 and an express server running on port 8000. I am trying to make a request from within my react app as follows: fetch('http://localhost:8000/login', { method: 'POST', headers ...

Retrieving the ID of a clicked button in React

I have a situation where I have 5 unique clickable links, each with their own distinct ID. My goal is to capture the specific ID of the link that was clicked. So far, I've experimented with two different methods but unfortunately, neither one has work ...

What is the best way to extract information from these JSON values?

My goal is to retrieve JSON values from a specific object. Here is the structure of this JSON data: { "attrs": { "width": 1728, "height": 787, "dragabble": true }, "className&qu ...

Why is my component not utilizing the implementation in this Jest mock?

I'm currently attempting to run tests on a React component using Jest. Within the component, there is a required module that acts as a factory function returning an object of functions. //tracker.js export default () => { track: click => doso ...

What iteration of the ECMAScript specification does the CEF platform accommodate?

Could you assist me in identifying the compatible version of ECMAScript in the chromium embedded framework (cef)? I am interested in utilizing ECMAScript 6 with it. ...

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

Obtaining the value of a variable beyond the asynchronous function immediately invoked expression

Having trouble accessing the value of con in other functions despite trying various methods like .thens and awaits from stack articles. Unfortunately, I keep encountering errors stating that con is not valid. Feeling stuck and unsure how to proceed with t ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

"Optimizing reload time for DIV content with jQuery's .load function is proving to be

I am currently facing an issue with a div that displays data from a database and a form that updates item quantities. After submitting the form, the div refreshes while a modal with a bootstrap spinner pops up to indicate it is loading. The problem arises ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

The value of req.body becomes null following a post request

I've been working on creating a contact form with the help of nodemailer. When trying to submit it using the fetch API, I encountered an issue where req.body is being returned as undefined. Below is the frontend code snippet: form.onsubmit = functio ...

Angularfire allows for easy and efficient updating of fields

Currently, I am working on creating a basic lateness tracker using AngularFire. So far, I have successfully added staff members to the miniApp and set the initial late minutes to a value of 0. My challenge lies in updating these values. Ideally, when a us ...

Utilizing the power of combined variables in Javascript

Is there a method to incorporate variables in each loop of a javascript loop? For instance, if I were to insert this code into a loop if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'} if (e2) {item_ ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I hav ...

How to include <li> in a preexisting <ul> using JSON data in jQuery

Here is the code snippet I am currently working with: <div id="tags"> <ul> </ul> </div> I want to add some items to the list using JSON data $.getJSON("data.json", function (data) { var html = ''; ...