Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to pass found string.replace value to function?

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

like image 807
Kebabbi Avatar asked Dec 09 '22 11:12

Kebabbi


2 Answers

When 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);
like image 107
Martin Jespersen Avatar answered Feb 08 '23 22:02

Martin Jespersen


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;});
like image 31
Vilx- Avatar answered Feb 08 '23 23:02

Vilx-