The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.
The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
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.
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);
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With