有这样一个字符串
如:
var str = "abc [1:hello] dasf [2:nice] abc [3:to] dasf [4:meet] sdf [5:you]";
[]里面的数字和":"后面的字符串不能确定,如何通过正则只替换最后一个匹配,如本 str 替换之后结果为"abc [1:hello] dasf [2:nice] abc [3:to] dasf [4:meet] sdf you";在线等候!! 请各位大侠帮帮忙啊

解决方案 »

  1.   

    正则不会用 lastindexof结合substring试试 
      

  2.   

    在我的应用中,其实有一个变量能够确定 [] 里面的数字,如:
    var itemNum = 5;
    var regEx = new RegExp("(\["+ itemNum +"\:)([^\]]+)(\])","igm");
    var str = "abc [1:hello] dasf [2:nice] abc [3:to] dasf [4:meet] sdf [5:you]";
    alert(str.replace(regEx,"$2"))可是上面的方法不能解决问题,不知错在哪
      

  3.   

     var str = "abc [1:hello] dasf [2:nice] abc [3:to] dasf [4:meet] sdf [5:you]";
     alert(str.replace(str.substring(str.lastIndexOf("[")),"you"));
      

  4.   

    使用new RegExp声明正则表达式时\需要转义var itemNum = 5;
    var regEx = new RegExp("(\\["+ itemNum +"\\:)([^\\]]+)\\]","ig");
    var str = "abc [1:hello] dasf [2:nice] abc [3:to] dasf [4:meet] sdf [5:you]";
    alert(str.replace(regEx,"$2"))