【问题标题】:javascript regex do not followed by specific characterjavascript regex 后面没有特定字符
【发布时间】:2020-03-04 08:11:23
【问题描述】:

我正在尝试通过 java-script 在这些单词上添加标记以作为商标符号

ABC®
ABC®/MD

这是我尝试过的。以下工作完美:

<div class="content-wrapper">
  ABC®/MD
</div>

$(".content-wrapper").each(function () {
  $(this).html($(this).html().replace(/®\/MD/g, "<sup>®</sup>"));
}

但是,我无法在相同的内容包装器中用&lt;sup&gt; 替换没有/MD®

<div class="content-wrapper">
  ABC®/MD
</div>

$(".content-wrapper").each(function () {
  $(this).html($(this).html().replace(/®?!\/MD/g, "<sup>®/MD</sup>"));
}

总而言之,如果匹配ABC®/MD,则结果应为ABC&lt;sup&gt;®/MD&lt;/sup&gt;,如果匹配ABC®,则输出应为ABC&lt;sup&gt;®&lt;/sup&gt;

【问题讨论】:

  • ®?!\/MD 匹配可选的®,然后匹配!/MD。你想做什么?为什么不在第二个 sn-p 中使用您的/®\/MD/g
  • 我只是想这样做,如果它匹配 ABC®/MD 然后添加 ABC®/MD 如果它匹配 ABC® 然后添加 ABC®支持>
  • /®\/MD/g 不能在第二个 sn-p 中使用,因为它与 ABC® 不匹配

标签: javascript jquery regex


【解决方案1】:

您可以使用可选组来匹配 ® ((?:\/MD)?) 之后出现的 1 次或 0 次 /MD,然后您需要替换为整个匹配的 $&amp; 反向引用:

.replace(/®(?:\/MD)?/g, "<sup>$&</sup>")

regex demo

JS 演示:

$(".content-wrapper").each(function () {
  $(this).html($(this).html().replace(/®(?:\/MD)?/g, "<sup>$&</sup>"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content-wrapper">
  ABC®/MD and ABC®
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 2014-03-22
    • 2011-09-06
    • 2021-08-06
    • 1970-01-01
    • 2020-05-15
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多