简体   繁体   English

Javascript和正则表达式替换文本

[英]Javascript and regex for replace text

Sir, I was doing a project with javascript .I want to replace a text with regex.in a paragraph i want to replace some word using javascript 先生,我正在用javascript做一个项目。我想用regex。替换一个文本,在一段中我想用javascript替换一些单词

eg: 例如:

 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");

Here all the " to " will be replaced.We don't want to remove between |code to code| 此处所有“ to ”将被替换。我们不想在| code to code |之间删除 Please help me any one..... 请任何人帮助我.....

I think you shouldn't rely on regexps for these kind of tasks, since it would be overcomplicated and therefore slow. 我认为您不应该依靠正则表达式来执行此类任务,因为它会过于复杂,因此速度很慢。 Anyway, if your expression is correct (ie, for every "|code" there's a "code|" and there aren't nested code tags), you can try this: 无论如何,如果您的表达式是正确的(即,对于每个"|code"都有一个"code|"并且没有嵌套的code标签),则可以尝试以下操作:

var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2");

Not only it's complicated, but it's hard to maintain. 这不仅很复杂,而且很难维护。 The best thing to do in these cases is to split your string to chunks: 在这些情况下,最好的做法是将字符串拆分为多个块:

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  "]

Note: str.replace("to", "2") does not replace every occurrence of "to" , but only the first one. 注: str.replace("to", "2")不能取代每次发生"to" ,但只有第一个。

if you want to replace all 'to' into 2 this will be the code 如果您想将所有“ 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM