简体   繁体   中英

Javascript RegExp help

I am trying to replace a certain text in Javascript.

newexp is a variable. numexp is a variable

replacenamestring = new RegExp('Memberresumeexp\[1\]',"ig");
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');

The above replace is not working.

How ever this works.

newexp = newexp.replace(/Memberresumeexp\[1\]/ig,'Memberresumeexp[' + numexp + ']');

Not able to figure out why?

Your first line creates a Javascript string, then parses the string as a regex.

Javascript string literals use \\ as an escape character, so the \\ s are not part of the string value. Therefore, the [ and ] in your regex aren't escaped, so it's creating a character class.
You need to escape the \\ s by writing \\\\ .

It's a simple lexical syntax issue. In the first case, you're creating the RegExp object with the constructor, which starts from a string constant. Well, string constants have their own syntactic quirks, and in particular those backslashes in the string will be interpreted during its own parsing. By the time the RegExp constructor is called, those are gone.

The "native" RegExp syntax has its own quoting rules, which are such that the "[" and "]" portions of the pattern are correctly interpreted when you use that syntax.

Here's a working example for you with one BIG caveat -- I changed "[1]" to "[\\d+]" just in case you needed this for more cases of Memberresumeexp[<any number>] . Also, I hardcoded numexp, because I had not seen how it was initialized.

var replacenamestring = new RegExp('Memberresumeexp\\[\\d+\\]',"ig");

var newexp = "asdfasdflkj;lakwjef Memberresumeexp[1] asdfasdfasdf\nqwerqwerwer Memberresumeexp[2] qwerqwerwqerewr\n";

var numexp = 123;
if(replacenamestring.test(newexp))
{
    newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM