0

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).

guypursey
  • 3,114
  • 3
  • 24
  • 42
  • 2
    JS strings are immutable, and the function *returns* a new string. – Bergi Feb 23 '13 at 12:19
  • 1
    Btw, instead of that function you could just use `"$1\\s*(.*)\\s*$2"` – Bergi Feb 23 '13 at 12:20
  • @Bergi Thanks. Was aware of the string alternative but am toying around with more complicated functions. Just wanted to get the basics right first. – guypursey Feb 23 '13 at 20:38

1 Answers1

1

String.replace() doesn't change the original string, but returns the new one. You should assign the result

for (i; i < r; i += 1) {
    str = str.replace(rex[i], function(star, p1, p2) {...})
}
  • So simple. I think the reference book I have throw me off as in none of the examples is a result assigned to a variable. Thanks. – guypursey Feb 23 '13 at 20:39