[removed] how to pass found string.replace value to function?

后端 未结 3 1742
-上瘾入骨i
-上瘾入骨i 2020-12-21 09:32

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 doe

3条回答
  •  温柔的废话
    2020-12-21 10:06

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

提交回复
热议问题