JavaScript strings have a cool method called replace()
which allows you to supply a regular expression and replace the matched bits of the string with another string.
var str = "my dog has fleas";
str = str.replace(/dog/, "cat");
Output:
my cat has fleas
One of the cooler things about this is you can provide an expression as the second argument. This can be a variable:
var str = "my dog has fleas";
var str2 = "cat"
str = str.replace(/dog/, str2);
...or even a function:
function Cat() {
return "cat";
}
str = str.replace(/dog/, Cat);
This works great in IE, and Firefox on both Windows and OS X.
But Safari? Not so much. Here's the output of that last example in Safari:
my function Cat() {return "cat";} has fleas
Ugh, what happened? It appears that when given a function in this context, Safari does not evaluate it as an expression, but instead calls the toString()
method of the function, casting it into a string.
I haven't found a workaround. Have you?