When I have something like this:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s){i++;return s;}('$1'));
alert(i);
Why does "i" equal 1 and not 4? Also, is it possible to pass the real value of $1 to a function (in this case 0,1,2,3) ?
When you use string.replace(rx,function)
then the function is called with the following arguments:
You can read all about it here
In your case $1 equals Match1, so you can rewrite your code to the following and it should work as you desire:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s,m1){i++;return m1;});
alert(i);
The expression
function(s){i++;return s;}('$1')
Creates the function and immediately evaluates it, passing $1
as an argument. The str.replace
method already receives a string as its second argument, not a function. I believe you want this:
str.replace(/(\d)/g,function(s){i++;return s;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With