You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):
"$TESTONE $TESTONE".replace(new RegExp("\\$TESTONE","gm"), "foo")
Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).
Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.
Answer from seth on Stack OverflowYou need to double escape any RegExp characters (once for the slash in the string and once for the regexp):
"$TESTONE $TESTONE".replace(new RegExp("\\$TESTONE","gm"), "foo")
Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).
Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.
In terms of pattern interpretation, there's no difference between the following forms:
/pattern/new RegExp("pattern")
If you want to replace a literal string using the replace method, I think you can just pass a string instead of a regexp to replace.
Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:
function reEscape(s) {
return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}
// ...
var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);
How Replace a string in regex
Regex advice - replace reoccurring strings in javascript
How do I incorporate in regular expressions ?
How do you replace a character in a string with a single backslash?
r/learnpython is probably a better subreddit for these kinds of questions.
Having said that, your first example actually works, try:
print("apple".replace('l', '\\')) More on reddit.com