JS正则 replace()方法全局替换变量(可以对变量进行全文替换)

转至:https://www.cnblogs.com/jasonlam/p/7070604.html

var text = "饿~,23333。饿~,测试yongde";
var word = "饿~"var newWorld = "额~~";
text = text.replace(word, newWorld);   // 只能替换第一个
text = text.replace(new RegExp(word,'g'), newWorld);  // 全局替换

利用 JS 的 RegExp 对象,将 g 参数单拿了出来,同时,正则的内容可以用变量来代替了!

猜你喜欢

转载自www.cnblogs.com/yhquan/p/10968052.html