0

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

coatless
  • 20,011
  • 13
  • 69
  • 84
  • `ctrl-f`? can you do this in the code base? – depperm Jul 12 '16 at 20:29
  • You can write a program to search and replace using regular expression in javascript, another way to use some editor such as notepad++ and do ctrl+f in all files as mentioned above. – WitVault Jul 12 '16 at 20:41
  • currently i am working with this for each replacement: https://jsfiddle.net/p4Lmea6v/ but i need a lot of more replacements like in the first post said. – Steelclover Jul 12 '16 at 20:43

2 Answers2

1

This is somewhat of a half answer. It shows the basic process, but also illustrates some of the inherent difficulties in a process like this. Detecting capitalization and properly formatting the replacements would be a bit intensive (probably utilizing something like this on a case-by-case basis How can I test if a letter in a string is uppercase or lowercase using JavaScript?). Also, when dealing with text nodes, innerHTML isn't an option, so the google replacement comes out as plain text instead of HTML.

TLDR - If you have another way to do this that doesn't involve javascript, do it that way.

var body = document.querySelector('body')

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}

function doReplacements(txt){
  txt = txt.replace(/sascha/gi, 'monika')
  txt = txt.replace(/mountain/gi, 'molehill')
  txt = txt.replace(/football/gi, 'soccer')
  txt = txt.replace(/google/gi, '<a href="http://www.google.com">google</a>')
  console.log(txt)
  return txt
}

var textnodes = textNodesUnder(body),
    len = textnodes.length,
    i = -1, node

console.log(textnodes)

while(++i < len){
  node = textnodes[i]
  
  node.textContent = doReplacements(node.textContent)
}
<div>Mountains of Sascha</div>
<h1>Playing football, google it.</h1>
<p>Sascha Mountain football google</p>
Community
  • 1
  • 1
jmcgriz
  • 2,819
  • 1
  • 9
  • 11
0

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();

Stefan Blamberg
  • 816
  • 9
  • 24
  • What if your word appears in an HTML attribute, or is a substring of an HTML tag etc? I recommend iterating through the DOM and replacing text nodes only. – le_m Jul 14 '16 at 23:27