簡體   English   中英

如何包裝包含在方括號內的內容,在所有出現的情況下使用字符串中的 span 標簽全局?

[英]How to wrap content,which is wrapped inside a squarebrackets, using span tag in a string gloabally for all the occurences?

我需要在字符串中突出顯示文本內容,該文本內容包含在方括號之間。 內容不止一次出現。 為此,我需要將其包裝在帶有一些 class 的跨度標簽中,以便為所有包裝在方括號 [] 內的內容突出顯示它。

我的字符串如下所示

let str = "<p>[If you no] longer wish to receive emails [from this sender] , pleas?ick here and confirm your [request] .</p>";

預期的結果是

let str = "<p><span class="highlight">[If you no]</span> longer wish to receive emails <span class="highlight">[from this sender]</span> , pleas?ick here and confirm your <span class="highlight">[request]</span> .</p>";

目前我正在做的方式如下

 let str = "<p>[If you no] longer wish to receive emails [from this sender], pleas?ick here and confirm your [request].</p>" let matched = str.match(/\[(.*?)\]/g); let someString=matched.map(element=> str.replace(element,`<span class="highlight">${element}</span>`) ) console.log(someString);

如果這種方法是錯誤的,那么請給出一些解決這個問題的最佳方法。 提前致謝。

替換中的$1將用於注入模式中第一個組中捕獲的元素。

在另一種情況下,如果您有另一個捕獲組,則替換為$2

MDN - RegExp.$1-$9

 let str = "<p>[If you no] longer wish to receive emails [from this sender], pleas?ick here and confirm your [request].</p>" let pattern = /\[(.*?)\]/g str = str.replace(pattern,'<span class="highlight">[$1]</span>') console.log(str) document.getElementById('result').innerHTML = str
 .highlight { background: yellow; }
 <div id="result"></div>

暫無
暫無

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

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