views:

3517

answers:

2

How do you replace all instances of one string with another in javascript? Example:

someString = 'the cat looks like a cat'
anotherString = someString.replace('cat', 'dog');

results in anotherString being set to 'the dog looks like a cat', and I would like it to be 'the dog looks like a dog'

+14  A: 

Using a regular expression with the g flag set will replace all:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

See also: http://www.tizag.com/javascriptT/javascript-string-replace.php

Adam A
Kinda silly I think, but the JS global regex is the only way to do multiple replaces.
Mike
+2  A: 

Match against a global regular expression:

anotherString = someString.replace(/cat/g, 'dog');
scronide