简体   繁体   English

RegEx jQuery:找到大写字母并忽略 html 标签

[英]RegEx jQuery: find the capital letters and ignore html tags

I want to target all capital letters and apostrophes an html string and leave out all the html tags.我想将所有大写字母和撇号定位为一个 html 字符串,并忽略所有 html 标签。 Indeed, content targeting between two rafters is not desirable because it causes bugs.事实上,两个椽子之间的内容定位是不可取的,因为它会导致错误。

Examples of strings to be addressed:要寻址的字符串示例:

Example 1:示例 1:

Test Drop Cap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777">Span</span> and more text<a href="#index-anchor" class="anchor"></a>

Example 2:示例 2:

Test Drop Cap with a <a href="https://github.com/Scriptura/Scriptura">Link</a> and that's it

Expected output is:预期输出为:

Example 1:示例 1:

<span class="letter">T</span>est <span class="letter">D</span>rop <span class="letter">C</span>ap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777"><span class="letter">S</span>pan</span> and more text<a href="#index-anchor" class="anchor"></a>

Example 2:示例 2:

<span class="letter">T</span>est <span class="letter">D</span>rop <span class="letter">C</span>ap with a <a href="https://github.com/Scriptura/Scriptura"><span class="letter">L</span>ink</a> and that's it

For now I got to do this:现在我必须这样做:

(function($){
    $.fn.letter = function(){
        $(':header, legend, .h1, .h2, .h3, .h4, .h5, .h6, .addletter').each(function(){
            var string = $(this);
            var newString = string.html().replace(/(<([^>]+)>|[A-Z«»"]|&amp;)/gm, '<span class="letter">$1</span>');
            string.html(newString);
        });
    };
    $('.letter').letter();
})(jQuery);

But my regex is not perfect: it also targets the content between two tags.但是我的正则表达式并不完美:它还针对两个标签之间的内容。 Could you help me make a better regex?你能帮我做一个更好的正则表达式吗? Thank you.谢谢你。

You may use this negative lookahead based regex.您可以使用这种基于负前瞻的正则表达式。

string.replace(/([A-Z])(?![^<>]*>)/g, '<span class="letter">$1</span>');

DEMO演示

 var s = 'Test Drop Cap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777">Span</span> and more text<a href="#index-anchor" class="anchor"></a>'; alert(s.replace(/([AZ])(?![^<>]*>)/g, '<span class="letter">$1</span>'))

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

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