首页 > 解决方案 > javascript regex 后面没有特定字符

问题描述

我正在尝试通过 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>"));
}

®但是,如果没有相同的内容包装器,我将无法替换/MD<sup>

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

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

总而言之,如果匹配,ABC®/MD则结果应该是ABC<sup>®/MD</sup>,如果匹配ABC®,则输出应该是ABC<sup>®</sup>

标签: javascriptjqueryregex

解决方案


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

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

查看正则表达式演示

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>


推荐阅读