-1

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");
}
Chi Le
  • 19
  • 6
  • One simple way of solving it is to replace ' has ' (with space before and after) with ' had '. A maybe better way would be using `replace()` with a RegExp like `/\bhas\b/g`. – secan Jul 26 '21 at 07:47

1 Answers1

2

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360