簡體   English   中英

正則表達式模式突出顯示雙引號內的序列字符串單詞

[英]regex pattern highlight n sequence string words inside double quotes

我的腳本突出顯示文本字符串中的特定單詞我唯一的問題是,當我想要突出顯示三個序列單詞時,它只突出顯示第一個單詞然后第二個單詞仍然沒有突出顯示然后第三個突出顯示

*它是一個截斷並且效果很好

? 突出顯示單詞+ n個字符

這是一個突出顯示n個序列詞的例子。 我的問題在這里我想強調""當我有雙引號時突出顯示引號內的單詞。

“參考是”需要突出顯示不分開的單詞

exp:參考好是test1 test2(這里只重點reference is

 var row = { "Abstract": "I have a reference server for reference and just a server here." }; //here i need to highlight "reference is" to serve test* (n sequnence words) var wordsToHighlight = '"reference is" to ser?? test*'; var result = row["Abstract"]; wordsToHighlight.split(" ").forEach(function (word) { word = word.replace(/\\*/g, '\\\\S*').replace(/\\?/g, '.').replace(/\\"/g, '.'); result = result.replace(new RegExp('(\\\\s|^)(' + word + ')(?=\\\\s|$)', "gi"),'$1<span style="background-color:yellow;">$2</span>'); }); document.querySelector("#result").innerHTML = result; 
 <div id="result"></div> 

您需要將原始wordsToHighlight字符串拆分為

.split(/"([^"]+)"|\s+/).filter(Boolean)

它將使用雙引號子串分割字符串,同時將雙引號之間的子字符串推入結果數組( String#split始終將捕獲的子字符串推送到結果數組中),並且使用1+空格和.filter(Boolean)將刪除空項在拆分操作期間可能會導致

請參閱正則表達式演示

JS演示:

 var row = { "Abstract": "This reference is to serve test as a useful reference for testing whether the styling of reference works or not. Adtest all occurrences of 'reference' should be given a color of red tests" }; //here i need to highlight "reference is" to serve test* (n sequnence words) var wordsToHighlight = '"reference is" to ser?? test*'; var result = row["Abstract"]; wordsToHighlight.split(/"([^"]+)"|\\s+/).filter(Boolean).forEach(function (word) { word = word.replace(/\\*/g, '\\\\S*').replace(/\\?/g, '.').replace(/\\"/g, '.'); result = result.replace(new RegExp('(\\\\s|^)(' + word + ')(?=\\\\s|$)', "gi"),'$1<span style="background-color:yellow;">$2</span>'); }); document.querySelector("#result").innerHTML = result; 
 <div id="result"></div> 

暫無
暫無

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

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