1

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

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| Please help me any one.....

2 Answers 2

1

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 (i.e., for every "|code" there's a "code|" and there aren't nested code tags), you can try this:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

if you want to replace all 'to' into 2 this will be the code

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.