简体   繁体   中英

Javascript - Replace text beetwen special characters

I'm trying to replace everything between special characters of a string in Javascript.

var text = "Hello,\n>> Someone lalalala\nMore Text\n<<";

I've tried the following code:

var newText = text.replace(/>>.*<</, ">>Some other text<<");

But at the end it actually returns the text variable.

I'd appreciate some thoughts about this. Thanks.

Regexes are "greedy", meaning they'll try to match the longest substring possible. Since .* means literally any character, it's going to include your delimiter << as well. Thus, .* reaches all the way to the end of your string, and then it can't find << after that, so the match will fail. You have to exclude it in your expression:

text.replace(/>>[^<]*<</, ">>Some other text<<");

The problem is that '.' does not match new lines. Using this answer :

 var text = "Hello,\\n>> Someone lalalala\\nMore Text\\n<<"; var newText = text.replace(/>>[\\s\\S]*<</m, ">>Some other text<<"); console.log(newText); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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