Skip to content Skip to sidebar Skip to footer

Censoring Words Within Html Page Using Javascript

I'm trying to make a function that gets a word and censors it in an html document but the function I made causes some problems if the word is contained within tags see code exampl

Solution 1:

You may write a function like this:

function censorWord(el, word) { 
  if (el.children.length > 0) { 
    Array.from(el.children).forEach(function(child){ 
      censorWord(child, word) 
    }) 
  } else { 
    if (el.innerText) { 
      el.innerText = el.innerText.replace(new RegExp(`\\b${word}\\b`, "g"), "***") 
    } 
  }  
}

and

censorWord(document.body, "someWord")


Post a Comment for "Censoring Words Within Html Page Using Javascript"