Search code examples
javascriptreplacesyntax-errortextnode

Javascript find-and-replace code in need of correction


The following code, included in the header of a website, contains errors. I think the intention is clear by the code, but that it contains syntactical and/or other errors? Please correct.

Edit 2: full minimal example (js fiddle: https://jsfiddle.net/g1u2p36k/):

<html>

<head>
<script language="javascript">
function walkText(node) {
  if (node.nodeType == 3) {
    node.data = node.data.replace(/"Ashen Glow Gaming"/gi, "<span style=\"font-color: red;\">a<span style=\"color: blue\">shen</span> g<span style=\"color: blue\">low</span> g<span style=\"color: blue\">aming</span></span>");
  }
  if (node.nodeType == 1 && node.nodeName != "SCRIPT") {
    for (var i = 0; i < node.childNodes.length; i++) {
      walkText(node.childNodes[i]);
    }
  }
}
walkText(document.body);
</script>
</head>

<body>
blah blah Ashen Glow Gaming <a href="https://www.ashenglowgaming.com" class="Ashen Glow Gaming">an ashen glow gaming link</a> blah blah
</body>
</html>

This should result in all instances of the string "Ashen Glow Gaming" being replaced with a specially formatted version in the text:

enter image description here

Edit: JSLint identified 2 instances of Expected '\s' and instead saw ' '. and one instance of Expected '/'.:

enter image description here


Solution

  • You are not escaping the quotes inside quotes.

    node.data = node.data.replace(/"Ashen Glow Gaming"/gi, "<span style=\"font-family: elektora;\">a<span style=\"font-size: 80%\">shen</span> g<span style=\"font-size: 80%\">low</span> g<span style=\"font-size: 80%\">aming</span></span>");