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 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) ?
Share Improve this question asked Jan 17, 2011 at 11:58 KebabbiKebabbi 1743 silver badges8 bronze badges 1- D'oh, the answer to the first part is because the inside function gets executed before the replace function gets the value. But I still don't know the answer to the second question. – Kebabbi Commented Jan 17, 2011 at 12:04
3 Answers
Reset to default 13When you use string.replace(rx,function)
then the function is called with the following arguments:
- The matched substring
- Match1,2,3,4 etc (parenthesized substring matches)
- The offset of the substring
- The full string
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;});
You are calling the function, which increments i
once, and then returns the string '$1'
.
To pass the value to a function, you can do:
str.replace(/\d/g, function (s) { /* do something with s */ });
However, it looks like you don't actually want to replace anything... you just want a count of the number of digits. If so, then replace
is the wrong tool. Try:
i = str.match(/\d/g).length;