使用 Javascript 用 <sup> 包装所有 regmarks;标签,除非他们已经有 <sup>标签 [英] use Javascript to wrap all regmarks with <sup> tags unless they already have <sup> tags

查看:19
本文介绍了使用 Javascript 用 <sup> 包装所有 regmarks;标签,除非他们已经有 <sup>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提前致谢.

我正在使用

  $(document).ready(function() {
           $("body").html(
    $("body").html().replace(/&reg;/gi, '<sup>&reg;</sup>').replace(/®/gi, '<sup>&reg;</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(/&reg;/gi, '<sup>&reg;</sup>').replace(/®/gi, '<sup>&reg;       
      </sup>').replace('<sup><sup>', '<sup>').replace('</sup></sup>', '</sup>'));
   });
 });

推荐答案

你想要这个:

$("body").html(
  $("body").html()
    .replace(/((?!<sup>\s*))&reg;((?!\s*<\/sup>))/gi, '<sup>&reg;</sup>') // wrap &reg; if not wrapped yet
    .replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>&reg;</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*))&reg;((?!\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*))&reg;((?!\s*<\/sup>))/gi, '<sup>&reg;</sup>')
    .replace(/((?!<sup>\s*))®((?!\s*<\/sup>))/gi, '<sup>&reg;</sup>');

<sup>&reg;</sup>
&reg;
<sup>®</sup>
®
<sup> &reg; </sup>
<sup> ® </sup>
<sup>
   &reg; 
</sup>
<sup> ® 
</sup>
"Buy more Emo&reg; Jeans!"

这篇关于使用 Javascript 用 &lt;sup&gt; 包装所有 regmarks;标签,除非他们已经有 &lt;sup&gt;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆