如何用jQuery在span标签中换行文本,除了第一个单词

How to wrap text in span tags except first word with jQuery?

本文关键字:文本 单词 第一个 换行 jQuery 何用 span 标签      更新时间:2023-09-26

是否可以将最后一个单词用span标签包装在字符串中,不包括第一个单词?例如:

var string = 'My super text';

My <span>super text</span>

我有这个:

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

如果至少有两个span标签,则用span标签包装最后一个单词,但不确定如何修改

您只需要使用将返回第一个单词的text.shift(),而不是返回最后一个单词的text.pop()。这样做就容易多了

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

您可以使用正则表达式。

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

但是,您可能应该将下面的代码转换为递归函数…

$('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 .

这将允许您修改文本节点和插入span元素,而不会扰乱序列化的HTML。

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

你不需要分割文本,只需要检查是否有空格,并在那里插入一个span

这段代码在第一个空格之后插入一个span,如果没有空格(idx == -1),则将span放在字符串的开头:

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