Unlike .NET C# (or most other programming languages), the Javascript replace function only replaces the first instance of a string. To replace all the instances, you need to use regular expressions.
Simon Willison's Weblog contains a good article on this.

Basically, if you use str1.replace(str2,str3) it will return str1 with the first occurence of str2 replaced with str3. If you use str1.replace(regexp1,str3) and the regular expression has the g modifier it will return str1 with all matches of regexp1 replaced with str3.

A regular expression looks like : /searchpattern/modifiers.
You can create a regular expression from a string by using the
new RegExp(str2,modifiers)
syntax.

The problem comes when you want to create a regular expression from a variable that may contain regular expression escape sequences. Here is Simon Willison's function that "escapes" the string in order to use the RegExp syntax safely, slightly modified to contain the '^' character:

RegExp.escape = function(text) {
if (!arguments.callee.sRE) {
var specials = [
'/', '.', '*', '+', '?', '<', '>',
'(', ')', '[', ']', '{', '}', '\\', '^'
];
arguments.callee.sRE = new RegExp(
'(\\' + specials.join('\\') + ')', 'g'
);
}
return text.replace(arguments.callee.sRE, '\\$1');
}


Example: str=str.replace(/\\/g,'\\\\') (replace slashes with double slashes)

Comments

Be the first to post a comment

Post a comment