Thursday, July 2, 2009

Javascipt Replace, Replace All

Working in javascript today,
I found out that in javascript, the replace function only replaces the first occurrence, not all as in c#/VB.
You can test this by pasting the following in the addressbar of (most) browsers:

javascript:alert('test-test-test'.replace('-',''));

To replace all occurrences you need to use regular expression (place the word you want to find between / /g :

javascript:alert('test-test-test'.replace(/-/g,''));


or you can create a javascript function eg:

function replaceAll(text, findText, replaceText)
{
return text.replace( new RegExp(findText,"g"), replaceText);
}