简体   繁体   中英

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. Indeed, content targeting between two rafters is not desirable because it causes bugs.

Examples of strings to be addressed:

Example 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:

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

Expected output is:

Example 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:

<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>'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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