簡體   English   中英

評論中的多個引號替換

[英]Multiple quotes in comments with replace

我需要改變這個:

[quote=mvneobux]My first comment[/quote]
I liked your comment.

在那里面:

<div class="quote">
    <div class="author">mvneobux:</div>
    My first comment.
</div>
I liked your comment.

當只有一個引用時,另一個主題中的解決方案日期非常有效。 但是兩個引號或更多引號不起作用。

目前代碼如下

comment.replace(/\[quote=(.+?)\](.+?)\[\/quote\]/, '<div class="quote"><div class="author"> $1 </div> $2 </div>');

但在以下情況下,結果被破壞:

[quote=username2][quote=mvneobux]interessante e bom continue[/quote][/quote]

我該如何解決? 請記住,彼此之間可能有多個引號。 我怎么能把每一個分開?

而不是使用.*? 要匹配中間的內容請將[quote=SOMETHING]的任何內容與((?:(?.\[quote)?)*?)匹配。 然后,一次替換一個,直到沒有更多匹配項:

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

另一種選擇是創建一個更簡單的 RegEx 表達式並結合使用簡單的替換,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM