Javascript: how to pass the found string.replace value for a 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 is "i" equal to 1, not 4? Also, is it possible to pass the actual value of $ 1 to a function (in this case, 0,1,2,3)?

+3
javascript function regex replace
source share
3 answers

When using string.replace(rx,function) function is called with the following arguments:

  • Matching Substring
  • Match1,2,3,4 etc. (matching substrings in brackets)
  • Substring offset
  • Full line

Here you can read all about it.

In your case, $ 1 is Match1, so you can rewrite your code to the following, and it should work as you wish:

 var str = "0123"; var i = 0; str.replace(/(\d)/g,function(s,m1){i++;return m1;}); alert(i); 
+12
source share

Expression

 function(s){i++;return s;}('$1') 

Creates a function and immediately evaluates it, passing $1 as an argument. The str.replace method already takes a string, not a function, as the second argument. I believe you want this:

 str.replace(/(\d)/g,function(s){i++;return s;}); 
+1
source share

You call a function that increments i once and then returns the string '$1' .

To pass the value of a function, you can:

 str.replace(/\d/g, function (s) { /* do something with s */ }); 

However, it looks like you really don't want to replace anything ... you just want to count the number of digits. If so, then replace is the wrong tool. Try:

 i = str.match(/\d/g).length; 
0
source share

All Articles