Steelclover Steelclover - 4 months ago 9
Javascript Question

Make a mountain out of a molehill by replacing it with JavaScript

I want to replace multiple words on a website with other words. That is, I am interested in finding all instances of a

source
word and replacing it with a
target
word.

Sample Cases:

Source | Target

Molehill => Mountain

Green => Grey

Google =>
<a href="http://google.com">


Sascha => Monika

Football => Soccer

Answer

Here is the JS:

function replaceWords () {
var toReplace = [
    ["Green","Grey"],
    ["Google","<a href='http://google.com'>"]
];
var input = document.getElementById("content").innerHTML;
console.log("Input: " + input);
for (var i = 0; i < toReplace.length; i++) {
    var reg = new RegExp(toReplace[i][0],"g");
    input = input.replace(reg,toReplace[i][1]);
}
document.getElementById("content").innerHTML = input;

};

replaceWords();

Comments