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:

  1. "cat" replaced "fish"
  2. "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

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -