简体   繁体   English

正则表达式向前看和向后看

[英]Regex lookahead AND lookbehind

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).我想用 JavaScript 将我网站上的所有®标志替换为<sup>®</sup> 。但我必须注意,只有在它们周围没有 sup 时才替换它们(可能来自 CMS 用户)。

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".它只关心</sup>标签并且在 Safari 中不起作用,原因是“无效的组说明符名称”。 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.交替逻辑首先急切地尝试查找<sup>®</sup>的出现。 That failing, it also tries to find any other ® occurrence.如果失败,它还会尝试查找任何其他®事件。 Then, in the callback, we wrap with <sup> tags only if not already wrapped.然后,在回调中,我们仅在尚未包装的情况下使用<sup>标签进行包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM