Search code examples
javascriptstringreplacesubstringreplaceall

Replacing a word with another word without replacing another word which contains a similar substring in the same sentence in Javascript


I'm trying to replace a word with another word, specifically "has" with "had". But the string contains the word "hash" which has the substring "has" so it also gets replaced. What can I do to fix this?

function replace() {
    sentence = sentence.replaceAll("has", "had");
}

Solution

  • Place word boundaries around the word to be replaced:

    var input = "A man who has an appetite ate hashed browns";
    var output = input.replace(/\bhas\b/g, "had");
    console.log(output);

    Note that I used regular replace along with the /g global flag. This should have the same behavior as using replaceAll.