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

后端 未结 3 1748
-上瘾入骨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:23

    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;
    

提交回复
热议问题