我想用正则表达式替换一些单词。
例如:
var str ="hello world |bo hello world bo| hello world |co hello world co| hello world,hello world |jp hello world hello world jp| "
var n=str.replace("world","stackoverflow");
但|bo ... bo|
,|co ... co|
,|jp ... jp|
内的内容不应修改为stackoverflow。
答案 0 :(得分:2)
使用/g
表示全局替换:
var n=str.replace(/world/g,"stackoverflow");
这是a working fiddle来演示。
其他信息
在RegEx标志上查看MDN for more information。
答案 1 :(得分:0)
考虑到这一点,它将“bb”替换为“xx”,而不是当“bb”被“a”包围时。
t = "bb abba bb abba bb";
t = t.replace(/(?!a)bb(?!a)/g, "xx");
// t === "xx abba xx abba xx"