js replace函数_JS中的Replace()传入函数时的用法详解

时间:2021-08-17  来源:正则表达式  阅读:

replace方法的语法是:stringObj.replace(rgExp, replaceText) 其中stringObj是字符串(string),reExp可以是正则表达式对象(RegExp)也可以是字符串(string),replaceText是替代查找到的字符串。。

废话不多说了,直接给大家贴代码了,具体代码如下所示:

 <script>
var str = "a1ba2b";
var reg = /a.b/g;
str = str.replace(reg,function(a,b){
 console.log(a);
 console.log(b);
 return b == 0 ? a.replace("a","0") : a.replace("b","3");
});
console.log(str);
/*
输出结果为:
a1b
0//第一次匹配到a1b,将a置为0.
a2b
3//第二次匹配到a2b,将b置为3.
01ba23//返回经过修改后的字符串
*/
/*
function(a,b,c)一共可以传入3个参数,第一个为匹配的字符串,第二个为匹配字符串的起始位置,
第三个为调用replace方法的字符串本身。可以缺省c或b、c。
*/
</script>

js replace函数_JS中的Replace()传入函数时的用法详解

http://m.bbyears.com/aspjiaocheng/136458.html

推荐访问:
相关阅读 猜你喜欢
本类排行 本类最新