爵士 我正在用javascript做一个项目。我想用regex.in替换一个段落的文本我想用javascript替换一些单词
例如:
var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions "
var n=str.replace("to","2");
此处所有“到”都会被替换。我们不想删除 | code 到代码| 请帮帮我任何人......
答案 0 :(得分:1)
我认为你不应该依赖regexp来完成这些任务,因为它会过于复杂,因此很慢。无论如何,如果你的表达是正确的(即每个"|code"
有一个"code|"
并且没有嵌套的code
标签),你可以试试这个:
var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2");
不仅复杂,而且很难维护。在这些情况下,最好的做法是将字符串拆分为块:
var chunks = [], i, p = 0, q = 0;
while ((p = str.indexOf("|code", p)) !== -1) {
if (q < p) chunks.push(str.substring(q, p));
q = str.indexOf("code|", p);
chunks.push(str.substring(p, p = q = q + 5));
}
if (q < str.length) chunks.push(str.substring(q));
// chunks === [" Would you like to have responses to your questions ",
// "|code Would you like to have responses to your questions code|",
// " Would you like to have responses to your questions "]
注意:str.replace("to", "2")
不会替换"to"
的每一次出现,而只替换第一次出现。
答案 1 :(得分:0)
如果你想将所有'to'替换成2,那将是代码
var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions";
var n=str.replace(/to/g,"2");