Skip to content Skip to sidebar Skip to footer

How To Wrap Text In Span Tags Except First Word With JQuery?

Is it possible to wrap the last words in a string with span tags excluding the first word? So it'd be for example: var string = 'My super text'; Becomes My super text&

Solution 1:

You just need to use text.shift() which will return the first word, instead of text.pop() which returns the last word. Then it will be much easier to accomplish this.

var text= string.split(" ");

// get the first word and store it in a variable
var first = text.shift();

// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
   return first + " <span>" + text.join(" ") + "</span>";
} else {
   return "<span>" + first + "</span>";
}

Solution 2:

You could do it with a regular expression.

text = text.replace(/\s(.*)$/, ' <span>$1</span>');

However, you should probably turn the following into a recursive function...

$('body').contents().filter(function() {
    return this.nodeType == 3;
}).each(function() {
    var node = this;
    // Normalise node.
    node.data = $.trim(node.data);

    node.data.replace(/\s+(.*)\s*$/, function(all, match, offset) {
        var chunk = node.splitText(offset);
        chunk.parentNode.removeChild(chunk);
        var span = document.createElement('span');
        span.appendChild(document.createTextNode(' ' + match));
        node.parentNode.appendChild(span);
    });
});

jsFiddle.

This will allow you to modify text nodes and insert the span elements without messing with serialised HTML.


Solution 3:

var space = string.indexOf(' ');

if (space !== -1) {
   return string.slice(0,space) + " <span>" + string.slice( space ) + "</span>";
} else {
   return "<span>" + string + "</span>";
}

Solution 4:

You don't have to split the text, just check if there is a space, and insert a span there.

This code inserts a span after the first space, and if there is no space (idx == -1), the span is put at the beginning of the string:

var idx = string.indexOf(' ');
return string.substr(0, idx + 1) + "<span>" + string.substr(idx + 1) + "</span>";

Post a Comment for "How To Wrap Text In Span Tags Except First Word With JQuery?"