I have an array of regular expressions, at the moment just one element in length, and a string which I want to search/replace by looping through the array:
var str = "i am*happy all the*time",
rex = [
/(\S)\s*\*\s*(\S)/g
],
i = 0,
r = rex.length;
This is how I'm trying to achieve this at the moment:
for (i; i < r; i += 1) {
str.replace(rex[i], function(star, p1, p2) {
console.log(i, star, p1, p2);
return p1 + '\\s*(.*)\\s*' + p2;
});
}
The result should be i am*\\s*(.*)\\s*happy all the\\s*(.*)\\s*time
. But at the moment, str
seems unaffected, even though when I check the console the relevant matches are being made. You can see this for yourself here.
So am I missing something simple, have I misunderstood something about using lambda expressions in String.replace(), or is there something more fundamentally wrong here?
...
EXTRA INFO: I'm using Chrome 24 right now, in case that's of interest; I had read a while ago that anonymous functions in String.replace() weren't available to all browsers though I assumed that would be resolved by now (the option was introduced in ECMAScript v3).