javascript - 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>
。
解决方案
您可以使用可选组来匹配出现的 1 次或 0 次/MD
after ®
( (?:\/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>
推荐阅读
- php - PDF 版 Google 视觉
- unity3d - 使用滑块更改游戏对象的位置
- python - 使用Django时如何正确存储excel文件
- mysql - 如何从具有以下关系的三个表中选择所有记录
- python - 如何将图形(3x3 子图)插入 matplotlib python 的子图中
- typescript - 有没有办法从 Firebase 函数访问 URL API?
- javascript - Javascript 磁贴不加载
- c - 如何在同一个包装函数中使用使用 malloc 的函数预加载共享库和包装 malloc?
- javascript - 对象数组值以样式元素
- sql - 从多个属性表中汇总历史数据