javascript 正则替换 replace(regExp, function)用法_javascript技巧

WBOY
Release: 2016-05-16 18:26:32
Original
1313 people have browsed it
复制代码代码如下:

function fn()
{
for(var i = 0;i   alert("第"+(i+1)+"个参数的值:"+arguments[i]);
  }
}
var str = '
{ni}
';
str.replace(/\{([a-z]+)\}/ig, fn);


根据多次测试由输出结果可以得出fn中:

  第一个参数为匹配到的字符串,如{wo}和{ni};

  第二个参数可以有0-N个,为第一个参数中匹配到一个括号正则的字符串,如第一个参数中的wo和ni,能匹配([a-z]+),

    括号有几组,则参数有几个;

  第三个参数为第一个参数中匹配到的字符串所在位置,如{wo}返回9,{no}返回16;

  第四个参数为用来匹配的字符串,在这个例子中就是
{ni}
.

本例中对于一个包含wo和ni的json对象可以简单地用:

复制代码代码如下:

str.replace(/\{([a-z]+)\}/ig, function(s, t){
return json[t];
});

来替换.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!