I want to replace all ®
signs on my website to an <sup>®</sup>
with JavaScript. But I have to care that I only replace them if there is no sup surrounding them already (maybe from CMS users).
I already tried the following but it does not work fine.
html.replace(/(?<.<sup>,{0?})®(.,,{0;}<\/sup>)/g, "<sup>®</sup>")
It does only care for the </sup>
Tag and does not work in Safari cause of an "invalid group specifier name". Maybe someone here can help me with this.
You could use a regex replace with an alternation and callback:
var input = "Hello ® and also <sup>®</sup>"; var output = input.replace(/<sup>®<\/sup>|®/g, (x) => x === "<sup>®</sup>"? x: "<sup>®</sup>"); console.log(output);
The alternation logic first eagerly attempts to find <sup>®</sup>
occurrences. That failing, it also tries to find any other ®
occurrence. Then, in the callback, we wrap with <sup>
tags only if not already wrapped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.