Using String prototype
A possible solution is defining a replaceAll function, e.g. in the prototype of String
:
String.prototype.replaceAll = function(search, replace) {
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
After this, you only need to iterate over the properties of charsToReplace
:
for (var prop in charsToReplace) {
if (charsToReplace.hasOwnProperty(prop)) {
str = str.replaceAll(prop, charsToReplace[prop]));
}
}
The final str
can be assigned to the innerHTML
.
Using normal function
If for some reason, you do not want to mess with the prototype, you may define a normal JavaScript function for the same task:
var replaceAll = function (str, search, replace) {
return str.replace(new RegeExp('[' + search + ']', 'g'), replace);
}
This works really the same way, you just need to pass the string instance to it:
str = replaceAll(str, prop, charsToReplace[prop]));
Another approach
If you would use these methods often, you might consider storing the regex patterns in your charsToReplace
object, like this:
var charsToReplace = {
'&': {
pattern: new RegExp('[' + '&' + ']', 'g'),
replace: '&'
}
...
}
So your replaceAll
function would look like this:
var replaceAll = function (str, replacement) {
return str.replace(replacement.pattern, replacement.replace);
}
This way you would not need to recreate the regular expressions every time, which could save some processing time.