是否可以使用 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 标签包裹最后一个单词。
最佳答案
您只需要使用返回第一个单词的 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>";
}
关于javascript - 如何使用 jQuery 在 span 标签中包装文本,除了第一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8441045/