Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap words in paragraph with span, keep nested links functioning

Tags:

html

jquery

split

How might I wrap every word in a paragraph with a span while keeping any nested links functioning? Using the code below from here I get close, but splitting on whitespace inserts a span between the a and the href resulting in something like this:

<p><span><a< span> <span>href="#"&gt;this</span></a<></span></p>

which obviously renders the link unusable.

$('p').each(function() {

var text = $(this).html().split(/\s+/),//split on space
    len = text.length,
    result = []; 

for( var i = 0; i < len; i++ ) {
    result[i] = '<span>' + text[i] + '</span>';
}
$(this).html(result.join(' '));
});

Jsfiddle here which perhaps better illustrates my point. Thanks!

like image 803
psflannery Avatar asked Jun 24 '26 09:06

psflannery


1 Answers

The problem is you don't want to randomly be inserting "<span>" tags inside of other tags. A resulting html like: <img <span>src="blahblah"</span>> is going to be an issue, were you ever to get one.

You can use a regex to match out the tags in the HTML and only add <span> tags to everything else. Probably not perfect, but something like:

$('p').each(function() {

    var tagRE = /([^<]*)(<(?:\"[^\"]*\"|'[^']*'|[^>'\"]*)*>)([^<]*)/g,
        match,
        result = [],
        i = 0;

    while(match = tagRE.exec($(this).html())) {
        var text1 = match[1].split(/\s+/),
            len1 = text1.length;

        var text2 = match[3].split(/\s+/),
            len2 = text2.length;

        for(var tIdx = 0; tIdx < len1; tIdx++ )
            result[i++] = '<span>' + text1[tIdx] + '</span>';           

        result[i++] = match[2];

        for(var tIdx = 0; tIdx < len2; tIdx++ )
            result[i++] = '<span>' + text2[tIdx] + '</span>';          
    }

    $(this).html(result.join(' '));

});

http://jsfiddle.net/5wabK/

It's probably a little inefficient but I had to use a group at the beginning and the end in order to capture everything before the first tag and after the last one.

like image 72
lc. Avatar answered Jun 25 '26 23:06

lc.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!