简体   繁体   中英

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 <span>super text</span>

I have this:

var text = string.split(" ");

// drop the last word and store it in a variable
var last = text.pop();

// 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 text.join(" ") + " <span>" + last + "</span>";
}
else {
   return "<span>" + text.join(" ") + last + "</span>";
}

Which wraps the last word with span tags if it has at least two but not sure how to modify it.

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>";
}

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.

var space = string.indexOf(' ');

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

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>";

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