我需要将特定颜色设置为特殊字符。

具体来说,我想在*中将星号<div>设置为red颜色,而无需直接干预<div>

在网上,我找到了这个项目,该项目实际上是为字符设置背景色,但是如果我将脚本修改为*符号,它将无法正常工作。

输出示例:

javascript - 如何选择字符串中的星号并设置其样式?-LMLPHP

$("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"/>

10-05 20:49
查看更多