[英]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.