简体   繁体   中英

replacing words in a web page with JS

I was trying to make a Firefox extension that filters out cuss words and as a test I made it try to filter out the word "the" and replace it with "!@#$", but when I ran it nothing happened I have no clue why. Could someone help? here's my code:

function replaceText(selector, text, newText, flags) {
  var matcher = new RegExp(text, flags);
  var elems = document.querySelectorAll(selector), i;

  for (i = 0; i < elems.length; i++)
    if (!elems[i].childNodes.length)
      elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText);
}

var selectorsToUse = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "a", ];
var curseWords= [["the" "!@#$"]]

for(curseRegex = 0; curseRegex < curseWords.length; curseRegex++;)
{
    for(i = 0; i < selectorsToUse.length; i++)
    {
        replaceText(selectorstouse[i], cursewords[curseregex][0],
        curseWords[curseRegex][1], "gi");
    };
};

I used someone else's code for the function by the way

All that code seems like a bit more work than is necessary. Try something simpler with a regular expression. For example, /the/ig . The expression (just a word in this case) is written between the forward slashes. The little i is for case insensitive, so "the", "THE", "The", and any other combination will always be matched. The little g is for global, so you can get ALL instances of "the" in the current string. In the event that you want to add more words, just add a | plus the next word, like /the|dog/ig . This can go on for as many words as you want. /the|dog|cow|cat/ig

Try this:

const curses = /the/ig
const filterStr = '!@#$'
const selectors = ['p', 'h1', 'a']

selectors.forEach(selector => {
  const elements = [...document.querySelectorAll(selector)] //convert node list to array
  elements.forEach(el =>
    el.textContent = el.textContent.replace(curses, filterStr))
})

Or ES5 if you prefer:

var curses = /the/ig;
var filterStr = '!@#$';
var selectors = ['p', 'h1', 'a'];

selectors.forEach( function(selector) {
  var elements = document.querySelectorAll(selector);
  elements = Array.prototype.slice.call(elements); //convert node list to array
  elements.forEach( function(el) {
    el.textContent = el.textContent.replace(curses, filterStr);
  })
})

Have a look at this codepen to play around with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM