代码之家  ›  专栏  ›  技术社区  ›  Mona Coder

字符串中加粗的特定字母[副本]

  •  1
  • Mona Coder  · 技术社区  · 6 年前

    这个问题已经有了答案:

    你能看看这个演示并告诉我怎么做吗 Bold 仅在具有该字符的元素组中的确切字母。

    请注意,我不愿意将整个字符串加粗(因为我现在可以更改整个字符串的字体粗细),但我只想将该字符加粗。为了使 a 只有这里。

    var boldLetter = "a";
     $("button").each(function(){
        if($(this).text().includes(boldLetter)){
           $(this).css('font-weight','bold');
        }
      });
    <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>
    1 回复  |  直到 6 年前
        1
  •  3
  •   Pranav C Balan Ansh Takalkar    6 年前

    文本换行方式 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?