简体   繁体   中英

Multiple quotes in comments with replace

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?

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

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

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