js replace whole word and not words within words
How to Replace a Whole Word and Not Words Within Words in JavaScript
If you have ever tried to replace a word in a string using JavaScript's replace()
method, you may have noticed that it replaces every occurrence of that word, even if it is part of another word. For example, if you try to replace the word "cat" in the sentence "I have a cat and a caterpillar", it will replace both "cat" and "caterpillar".
This can be frustrating if you only want to replace whole words. Fortunately, there are a few ways to achieve this.
Using Regular Expressions
One way to replace whole words is to use regular expressions with the word boundary anchor \b
. This matches the beginning or end of a word, without including any non-word characters such as whitespace or punctuation.
const sentence = "I have a cat and a caterpillar";
const newSentence = sentence.replace(/\bcat\b/g, "dog");
console.log(newSentence); // "I have a dog and a caterpillar"
In this example, we used the regular expression /\bcat\b/g
to match the whole word "cat" and replaced it with "dog". The g
flag at the end of the expression makes sure that all occurrences of the word are replaced, not just the first one.
Using Word Boundaries
If you don't want to use regular expressions, you can also use the indexOf()
method to find the position of the word in the string and check if it is surrounded by word boundaries.
const sentence = "I have a cat and a caterpillar";
const word = "cat";
const index = sentence.indexOf(word);
if (index !== -1 &&
((index === 0 || !/\w/.test(sentence[index - 1])) &&
((index + word.length === sentence.length) || !/\w/.test(sentence[index + word.length]))
)) {
const newSentence = sentence.slice(0, index) + "dog" + sentence.slice(index + word.length);
console.log(newSentence); // "I have a dog and a caterpillar"
}
In this example, we first find the index of the word "cat" using indexOf()
. We then check if it is not -1 (meaning it was found in the string) and if it is surrounded by word boundaries. We do this by checking if the character before and after the word are not word characters using the regular expression /\w/
. If the word is surrounded by word boundaries, we replace it with "dog" using slice()
.
Conclusion
Both of these methods allow you to replace whole words in a string without replacing words within words. Regular expressions provide a more concise solution, but may be harder to understand for beginners. Using word boundaries may be more verbose, but easier to understand.