簡體   English   中英

將所有出現的單詞替換為該單詞周圍的span標簽。 不區分大小寫

[英]Replace all occurrences of a word with a span tag around that word. Case insensitive

我想在帶有span標簽的字符串中包含所有出現的單詞。 無論案例敏感性如何。 並且跨度應該圍繞實際發生的單詞。 這個詞是可變的。

let title = "TEST word test word Test word tesT";
let regex = new RegExp(keyword, "g");
let titleToDisplay = title.replace(regex, `<span class="searchedTerm">${keyword}</span>`);
//here keyword is 'test' for example. i want to wrap all the occurrences with span.

您可以通過將'gi'作為第二個參數傳遞給RegExp構造函數來全局匹配單詞test並忽略大小寫。 然后使用$&來引用匹配的關鍵字,就像這樣

 let title = "TEST word test word Test word tesT"; let regex = new RegExp(/test/, "gi"); let titleToDisplay = title.replace(regex, '<span class="searchedTerm">$&</span>'); console.log(titleToDisplay); 

您可以使用“ 切換字符串中的單詞 ”。

基本上,用括號包裝關鍵字(無論它將是什么)並使用$1將其替換為實際創建的單詞。

 let keyword = 'test'; let title = "TEST word test word Test word tesT"; let regex = new RegExp(`(${keyword})`, "ig"); let titleToDisplay = title.replace(regex, '<span class="searchedTerm">$1</span>'); console.log(titleToDisplay); 

暫無
暫無

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

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