Reputation: 68
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.
Upvotes: 1
Views: 36
Reputation: 1984
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);
Upvotes: 0
Reputation: 4106
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<<");
Upvotes: 3