0
var newWord = prompt("What word do you want to block?");
var myRegExp = new RegExp("\b" + newWord + "\b", "ig");
var myString = "This is a test. To replace the word test with something other than test.";

function replaceString(string) {
  var newString = string.replace(myRegExp, "**");
  document.getElementById("output").innerHTML = newString;
}

replaceString(myString);

I am practicing with RegEx's and have been stumped. This is just a sample of the type of code I am trying to write. Essentially, I want to take input from a prompt and store that in the newWord variable. I then use that variable inside a RegEx and then replace that value of that RegEx (for example the word "test") with "**".

I have no problem with this code when I just use new RegExp(newWord, "ig");. The problem arises when I try to add word boundaries around the variable. I have tried multiple ways and have searched for the answer but have come up dry. Would anyone be able to explain what I am doing wrong? Thanks!

0 Answers0