Javascript:如何将发现的string.replace值传递给函数? [英] Javascript: how to pass found string.replace value to function?

查看:103
本文介绍了Javascript:如何将发现的string.replace值传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有这样的事情时:

  var str =0123; 
var i = 0;
str.replace(/(\d)/ g,function(s){i ++; return s;}('$ 1'));
alert(i);

为什么i等于1而不是4?
另外,是否有可能将$ 1的实际值传递给函数(本例中为0,1,2,3)?

解决方案 当使用 string.replace(rx,function)时,函数被调用以下参数:


  • 匹配的子字符串

  • Match1,2,3,4等(括号中的子字符串匹配)
  • 子字符串的偏移量
  • 完整字符串



  • 您可以在这里阅读所有内容



    <在你的情况下,$ 1等于Match1,所以你可以重写你的代码到下面,它应该按照你的愿望工作:

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


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

    这篇关于Javascript:如何将发现的string.replace值传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆