According to the String.prototype.replace()
page on MDN, I should be able to easily replace multiple patterns just by using
str.replace('what to replace', 'replace with', 'flags')
and setting the flags to 'g'
.
It works perfect in Firefox 3.6. But in Chrome and IE8, it only replaces the first 'what to replace'
.
I can use the
str.replace(/what to replace/gi, 'replace with')
syntax. But I'm pulling the 'what to replace'
out of an array, which makes it hard to add the flags in that syntax.
Here's the code I'm trying to use. How to I modify it to work in Chrome as well as Firefox?
function generateQuestion()
{
//alert('variable length: '+variableList.length);
for(i=0;i<variableList.length;i++)
{
variable = variableList[i];
rep = replacementList[i];
flags = "gi";
questionText = questionText.replace(variable, rep, flags);
}
}
And why do I have to bother modifying it at all? Shouldn't Chrome evaluate the JavaScript as described in the link?
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')
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
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.
To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.
The very page you linked to mentions:
The use of the flags parameter in the String.replace method is non-standard. For cross-browser compatibility, use a RegExp object with corresponding flags.
Basically, it should only work on Firefox. As per the documentation, you can generate regexes dynamically using new RegExp
:
var regex = new RegExp(variable, 'gi');
questionText = questionText.replace(regex, rep);
This will need variable
to be escaped, however.
It appears that webkit's implementation of string.replace perhaps doesn't have the 3rd parameter, as 'foo'.replace('o','i','g')
results in fio
for me.
The following appears to work however:
'foo'.replace(/o/gi,'i')
Another option is:
'foo'.replace(new RegExp('o', 'gi'),'i')
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