Filinto Muller
Filinto Muller

Reputation: 68

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.

Upvotes: 1

Views: 36

Answers (2)

raul.vila
raul.vila

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

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

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

Related Questions