Javascript replace string which doesn't match? -
say have string:
cat hates dog when replace :
str = str.replace('cat', 'fish'); i "cat" replaced "fish" , how works this:
- "cat" replaced "fish"
- "other string"(else) replaced "goat"
so new string:
fish goat goat
you can use regexp \b\w+?\b:
"cat hates dog".replace(/\b\w+?\b/g, function(a) { return === 'cat' ? 'fish' : 'goat'; }); it match every word (sequence of word characters \w surrounded word boundary \b) , pass match results in replace callback;
output:
fish goat goat
Comments
Post a Comment