Home > Blockchain >  Regex lookahead AND lookbehind
Regex lookahead AND lookbehind

Time:03-07

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>&reg;</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.

CodePudding user response:

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.

  • Related