javascript regex do not followed by specific character

Jass Preet :

I am trying to add tag via java-script on these words for trademark symbols

ABC®
ABC®/MD

Here what I tried. The following works perfectly:

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

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

However, I am not able to replace ® without /MD with <sup> in same content-wrapper:

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

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

To sum it up, if it matches ABC®/MD then the result should be ABC<sup>®/MD</sup> and if it matches ABC® then the output should be ABC<sup>®</sup>.

Wiktor Stribiżew :

You may use an optional group to match 1 or 0 occurrences of /MD after ® ((?:\/MD)?) and then you need to replace with a $& backreference to the whole match:

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

See the regex demo

JS demo:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198552&siteId=1