2

Say I have this string:

cat hates dog

When i do a replace :

str = str.replace('cat', 'fish');

I will only get "cat" replaced by "fish" , how to get it works like this:

  1. "cat" replaced by "fish"
  2. "other string"(else) replaced by "goat"

so I will get new string:

fish goat goat

1 Answer 1

4

You can use this regexp \b\w+?\b:

"cat hates dog".replace(/\b\w+?\b/g, function(a) {
    return a === 'cat' ? 'fish' : 'goat';
});

It will match every word (sequence of word characters \w surrounded by word boundary \b) and pass match results in replace callback;

Output:

fish goat goat
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.