String.replace('…','…')
var foo = 'It\'s the end of the world as we know it, and I feel fine.';
var result = foo.replace('end','BEGINNING');
"It's the BEGINNING of the world as we know it, and I feel fine."
it's basic, and it works in just about every browser.
String.replace(/…/,'…')
var vowels = /[aeiou]/gi;
result = foo.replace(vowels,'-');
"-t's th- -nd -f th- w-rld -s w- kn-w -t, -nd - f--l f-n-."
also well supported by browsers.
String.replace(/…/,myFunction)
function Capitalize(s){
return s.toUpperCase();
}
result = foo.replace(vowels,Capitalize);
"It's thE End Of thE wOrld As wE knOw It, And I fEEl fInE."
IEMac (5.2.2) and Safari (1.0b2) do not support supplying a function for the second parameter. Instead .toString() is applied to the function, resulting in the raw code of the function being used in the replacement.
String.replace(/…/,myFunction)
, using RegExp
function Capitalize(){
return RegExp.$1.toUpperCase()+RegExp.$2;
}
result = foo.replace(/([aeiou])([a-z])/g,Capitalize);
"It's the End Of the wOrld As we knOw It, And I fEel fIne."
In addition to the IEMac's and Safari's problem mentioned above, IEWin does not seem to populate the RegExp
object when a regular expression is used inside .replace()
. IEWin has major problems with this. Mozilla alone gets all four tests correct.
String.replace(/…/,myFunction)
, using parametersfunction Capitalize(orig,re1,re2){
return re1.toUpperCase()+re2;
}
result = foo.replace(/([aeiou])([a-z])/g,Capitalize);
"It's the End Of the wOrld As we knOw It, And I fEel fIne."
IEWin gets this one right. This is the proper method that works in all browsers which support using a function as the second parameter. (Plus, it's faster than attempting to use RegExp.$x
as above.)