2 回答
TA贡献1794条经验 获得超8个赞
您需要转义星号,因为它在正则表达式中也很重要。使用\\*:
编辑:按照@DBS的建议,最好在突出显示功能本身中添加此转义检查。代码已修改。
jQuery.fn.highlight = function(str, className) {
var escapeRegExp = function(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
var regex = new RegExp(escapeRegExp(str), "gi");
return this.each(function() {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {
return "<span class=\"" + className + "\">" + matched + "</span>";
});
});
};
$("p").highlight("*", "highlight");
$("label").highlight("*", "highlight");
span.highlight {
padding: 5px;
display: inline-block;
color: #F60;
}
p {
font-family: Verdana;
}
input::placeholder {
color: #F60;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Let's *go Zapata let's do it for the revolution, Zapatistas*!!!
</p>
<label for="txt">Email* </label>
<input placeholder="Email*" type="text" id="txt"/>
- 2 回答
- 0 关注
- 107 浏览
添加回答
举报