我在这里有一个列表,我想在每个单词上写出“大胆的”字样。胆大。
<ul id = "list">
<li>Make this word Bold</li>
<li>Bold this as well</li>
<ul>
JS:
$('#list li').each(function () {
var text = $(this).text();
var value = 'bold';
if (text.toLowerCase().indexOf(value) > -1) {
var html = $(this).html();
$(this).html(html.replace(value, "<span id='highlight' style='font-weight: bold'>" + value + "</span>"));
}
});
所以输出结果为:
将此字改为 Bold
大胆这个
如何修复我的代码?
答案 0 :(得分:4)
使用正则表达式,您可以使用bold
选择g
,(多次出现,使用i
选项,而不区分大小写)。然后,使用括号捕获原始单词,并使用$1
重用它:
var regex = new RegExp("(" + value + ")", "gi");
$(this).html( $(this).html().replace(regex, "<b>$1</b>") );
但是如果关键字出现在标记中,则替换.html()
可能会导致有趣的事情发生,即:
<span style="font-weight:<b>bold</b>"></span>
$('#list li').each(function() {
var text = $(this).text();
var value = 'bold';
var regex = new RegExp("(" + value + ")", "gi");
if (text.toLowerCase().indexOf(value) > -1) {
$(this).html( $(this).html().replace(regex, "<b>$1</b>") );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul id="list">
<li>Make this word Bold</li>
<li>Bold this as well</li>
<li>BOLD, bOld and bold also get BOld!</li>
<li><span style="font-weight:bold">This whole sentence is <b>NOT</b> bold because the style attribute was modified. Doh!</span></li>
</ul>
为避免这种情况,更准确的正则表达式版本是检查关键字是否附加<>
:
var regex = new RegExp("(" + value + ")(?![^<]*>|[^<>]*<\/)", "gi");
$('#list li').each(function() {
var text = $(this).text();
var value = 'bold';
var regex = new RegExp("(" + value + ")(?![^<]*>|[^<>]*<\/)", "gi");
if (text.toLowerCase().indexOf(value) > -1) {
$(this).html( $(this).html().replace(regex, "<b>$1</b>") );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul id="list">
<li>Make this word Bold</li>
<li>Bold this as well</li>
<li>BOLD, bOld and bold also get BOld!</li>
<li><span style="font-weight:bold">This whole sentence is bold because the style attribute was not modified. Yay!</span></li>
</ul>