我試圖用 HTML 標記包圍一些單詞,同時保留它們的大小寫。
例如
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
我正在尋找的輸出是這樣的
foo <span class="k">key</span> bar <span class="k">Key</span> hello <span class="k">kEY</span> world
我嘗試使用替換功能,但它影響了案例
str = str.replace(regex, '<span >key</span>');
輸出
foo <span class="k">key</span> bar <span class="k">key</span> hello <span class="k">key</span> world
<!-- all lower case :( -->
我也試過這個
let matches = regex.exec(str);
if (matches != null)
matches.forEach(match => str = str.replace(new RegExp(match, 'g'), '<span >' match '</span>');
但有些情況仍然被忽略。輸出
foo <span class="k">key</span> bar Key hello kEY world
<!-- only lower case is matched :( -->
有沒有辦法制作這樣的東西
str.replace(regex, the_matched_regex 'some text');
順便說一句,我事先不知道可能的情況,也不知道這個詞......我正在制作一個函式來突出顯示字串中鍵的匹配項,忽略搜索中的大小寫,在輸出中保留大小寫。
function highlight(src, key) {
/* some code */
return result;
}
uj5u.com熱心網友回復:
您可以在函式的第二個引數中使用行內replace函式
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
str = str.replace(regex, function(match) {
return "<span class='k'>" match "</span>";
});
console.log(str)
uj5u.com熱心網友回復:
您可以在實際匹配中使用占位符而不是靜態字串replace:
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
str = str.replace(regex, '<span >$&</span>');
console.log(str)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/469236.html
標籤:javascript 正则表达式 细绳 代替
