I want to replace all occurences of a pattern in a string by another string. For example, lets convert all “$” to “!”:
"$$$" -> "!!!"
Plain string.replace replaces only the first match:
"$$$".replace("$", "!"); // gives "$!!"
and regexes force me to escape to special chars
"$$$".replace(/\$/g, "!"); // Pattern is now full of backslashes!
Is it possible to do the global replacement without having to manually escape the special characters? I have a bunch of patterns is a part of my code and I think readability would suffer if had to escape all of them by hand.
I’m expecting either a trick that directly does what I want or at least a way to convert a string to an excaped form useable by new RegExp
There is no standard regexp escape function in Javascript.
You can write your own (source) or get it from your library (dojo example)
This allows us to create the custom regex object at runtime