0

I'm experiencing some understanding problem of javascript RegExp behavior. Please help me to get how this stuff works.

var str = "_prefix_123 blah blah _prefix_321 blah blah blah _prefix_100500";
var prefix = "_prefix_";
var exp = new RegExp (prefix+"\d*","gm");

str1 = str.replace(exp,"hello");
alert(str1);

str2 = str.replace(/_prefix_\d*/gm, "hello");
alert(str2);

check the fiddle here http://jsfiddle.net/6PSdg/4/

For some reason two identical (at least they seem like) regex patterns return different results. Can anyone explain what's going on? ))

Thanx!

0

1 Answer 1

2

The difference is that when you use the RegExp constructor, you're passing in a string, and backslashes in string literals are interpreted as string escapes. So to actually pass a backslash to the regex engine, you have to make sure the backslash in the string is escaped (by putting a backslash in front of it):

var exp = new RegExp (prefix+"\\d*","gm");
// Here ----------------------^

Updated Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.