Reputation: 59
I need to transform this:
[quote=mvneobux]My first comment[/quote]
I liked your comment.
In that:
<div class="quote">
<div class="author">mvneobux:</div>
My first comment.
</div>
I liked your comment.
the solution date in another topic works perfectly when there is only one quote. but two quotes or more don't work.
The current code is as follows
comment.replace(/\[quote=(.+?)\](.+?)\[\/quote\]/, '<div class="quote"><div class="author"> $1 </div> $2 </div>');
but in the following scenario the result is broken:
[quote=username2][quote=mvneobux]interessante e bom continue[/quote][/quote]
How can I solve? remembering that there may be several quotes within each other. How could I take each one separately?
Upvotes: 0
Views: 64
Reputation: 370879
Instead of using .*?
to match the content in the middle, match anything but [quote=SOMETHING]
with ((?:(?!\[quote).)*?)
. Then, replace one at a time, until there are no more matches:
let str = `[quote=mvneobux][quote=charlote]parabens pelo relato[/quote] legal seu relato[/quote]interessante`;
const pattern = /\[quote=([^\]]+)\]((?:(?!\[quote).)*?)\[\/quote\]/;
while (pattern.test(str)) {
str = str.replace(pattern, '<div class="quote"><div class="author">$1</div>$2</div>');
}
console.log(str);
Upvotes: 1
Reputation: 20014
Another options is just creating a simpler RegEx expression and use a simple replace in combination like
let result = `[quote=mvneobux]My first comment[/quote]
I liked your comment.`
.replace(/\[quote=(.+?)\]/,"<div class='author'>$1<div>")
.replace("[/quote]", "<div>");
console.log(result);
Upvotes: 0