[英]How to make many words bold in a sentence with regex?
我正在使用正則表達式將單詞周圍的雙下划線替換為粗體標簽。 但是,如果我在一個句子中用粗體顯示了一個單詞,那么它將無法正常工作。 例如:
"this should be __bold__ and __this__ also".replace(/\__([^*]+)\__/g,"<b>$1</b>");
我得到這個:
"this should be <span>bold__ and __this</span> also"
但是我想得到這個:
"this should be <span>bold</span> and <span>this</span> also"
我的正則表達式有問題。 目前,只有在句子中只有一個粗體字時,它才有效。
在正則表達式中,量詞+
和*
是“貪婪的”,這意味着它們將消耗盡可能多的與要量化的表達式匹配的字符。 您可以附加問號運算符?
將“貪婪”操作轉變為惰性操作。
這將使您的表達如下:
/\__([^*]+?)\__/g
有關更多信息,請訪問http://www.regular-expressions.info/repeat.html#lazy
您是否將雙下划線替換為__this__
變為<b>this</b>
類的粗體標記? 你可以這樣做,
"this should be __bold__ and __this__ also".replace(/__([^ ]+)__/g,"<b>$1</b>");
代替[^*]
,您可以執行[^ ]
排除所有空格。
作為稍微不同的解決方案,請嘗試以下正則表達式:
/__(.*?)__/g
請參閱此處的說明: https : //regex101.com/r/7CVJyd/1
let str = "this should be __bold__ and __this__ also"; str = str.replace(/__(.*?)__/g,"<b>$1</b>"); console.log(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.