使用 Javascript 用 <sup> 包装所有 regmarks;标签,除非他们已经有 <sup>标签 [英] use Javascript to wrap all regmarks with <sup> tags unless they already have <sup> tags
问题描述
提前致谢.
我正在使用
$(document).ready(function() {
$("body").html(
$("body").html().replace(/®/gi, '<sup>®</sup>').replace(/®/gi, '<sup>®</sup>')
);
});
在 regmarks 周围添加下标,但如果 ®标记已经具有 <sup > </up > 标签,它添加了两次上标.任何人都可以帮我添加一个检查以阻止它是否已经存在?
to add a subscript around regmarks, but if the ® marks already has the < sup > < / up > tags, it is adding the superscript twice. Can anyone help me with add a check to stop if its already there?
更新::我最终使用了这段代码,因为下面的答案干扰了我的 javascript 的其余部分.
update:: I ended up using this code because the answers below were interfering with the rest of my javascript.
$(document).ready(function() {
$("p,h1,h2,h3,h4, td").each(function(){
$(this).html($(this).html().replace(/®/gi, '<sup>®</sup>').replace(/®/gi, '<sup>®
</sup>').replace('<sup><sup>', '<sup>').replace('</sup></sup>', '</sup>'));
});
});
推荐答案
你想要这个:
$("body").html(
$("body").html()
.replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>®</sup>') // wrap ® if not wrapped yet
.replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>®</sup>') // wrap ® if not wrapped yet
);
说明:
您可以在正则表达式本身中为包装标签构建测试,而不是按照其他人的建议并在事后删除重复项.
Rather than doing what other folks have suggested and removing the duplicates after the fact you can build the test for the wrapped tag in the regex itself.
例如,这个正则表达式只找到没有被SUP
标签包围的字符(实体):
For example, this regex only finds the character (entity) when it is not surrounded by SUP
tags:
/((?!\s*))®((?!\s*<\/sup>))/gi
和/((?!\s*))®((?!\s*<\/sup>))/gi
JsFiddle 演示:http://jsfiddle.net/co3sy5zo/
JsFiddle demo: http://jsfiddle.net/co3sy5zo/
Runnable Snippet:(使用原生 javascript 而不是 jQuery)
Runnable Snippet: (uses native javascript instead of jQuery)
document.body.innerHTML =
document.body.innerHTML
.replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>®</sup>')
.replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>®</sup>');
<sup>®</sup>
®
<sup>®</sup>
®
<sup> ® </sup>
<sup> ® </sup>
<sup>
®
</sup>
<sup> ®
</sup>
"Buy more Emo® Jeans!"
这篇关于使用 Javascript 用 <sup> 包装所有 regmarks;标签,除非他们已经有 <sup>标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!