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\',
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')
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.
From Mozilla Developer Network - JavaScript - String - replace
Non-standard
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.
Working in Chrome and Firefox
To get your code to work in Chrome and Firefox, you'll have to create a RegExp object (since your strings aren't hardcoded) with the appropriate flags. See Mozilla Developer Network - RegExp