文本换行方式
strong
标记以获得结果。用于迭代和更新HTML内容
html()
方法,该方法的回调在内部迭代并用返回值更新内容。用于包装字符
String#replace
方法。
为了替换多次出现的情况,需要使用
RegExp
带有全局标志(添加
i
因为忽略了案例)所以使用
RegExp
constructor
.
var boldLetter = "a";
$("button").html(function(_, html) {
return html.replace(new RegExp(boldLetter, 'gi'), '<strong>$&</strong>');
});
var boldLetter = "a";
$("button").html(function(_, html) {
return html.replace(new RegExp(boldLetter, 'gi'), '<strong>$&</strong>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button">Afghanistan</button>
<button type="button">Antarctica</button>
<button type="button">Mali</button>
<button type="button">Canada</button>
<button type="button">US</button>
<button type="button">France</button>
<button type="button">Chile</button>
<button type="button">Peru</button>
或者用一个跨度
style
属性。
var boldLetter = "a";
$("button").html(function(_, html) {
return html.replace(new RegExp(boldLetter, 'gi'), '<span style="font-weight:bold">$&</span>');
});
var boldLetter = "a";
$("button").html(function(_, html) {
return html.replace(new RegExp(boldLetter, 'gi'), '<span style="font-weight:bold">$&</span>');
});
<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<button type=“button”>阿富汗</button>
<button type=“button”>南极洲</button>
<button type=“button”>马里</button>
<button type=“button”>加拿大</button>
<button type=“button”>美国</button>
<button type=“button”>法国</button>
<button type=“button”>智利</button>
<button type=“button”>秘鲁</button>
FY:
如果字符串包含在正则表达式中有特殊意义的内容,则必须使用
\\
.
参考:
Is there a RegExp.escape function in Javascript?