我需要为特殊字符设置特定颜色。
具体来说,我想设置星号 *
在 <div>
上色 red
,而不直接干预 <div>
.
我在网上找到了这个元素,它实际上是为字符设置背景颜色,但是如果我将脚本改编为 * 符号,它就不起作用。
输出示例:
$("p").highlight("*","highlight");
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
});
};
$("p").highlight("*","highlight");
span.highlight{
background:#F60;
padding:5px;
display:inline-block;
color:#FFF;
}
p{
font-family:Verdana;
}
<p>
Let's *go Zapata let's do it for the revolution, Zapatistas*!!!
</p>
如果代替 Z
我加了星号*
该脚本不起作用。有人可以帮忙吗?
最佳答案
您需要转义星号,因为它在正则表达式中也很重要。使用 \\*
:
编辑:按照@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"/>
关于javascript - 如何在字符串中选择星号并设置其样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61232892/