如何使用 jQuery 在跨度标签中包装文本,除了第一个单词? [英] How to wrap text in span tags except first word with jQuery?

查看:28
本文介绍了如何使用 jQuery 在跨度标签中包装文本,除了第一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

成为

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 标签包装最后一个单词.

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

推荐答案

你只需要使用 text.shift() 它将返回第一个单词,而不是 text.pop() 返回最后一个单词.那么实现这一点就会容易得多.

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

这篇关于如何使用 jQuery 在跨度标签中包装文本,除了第一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆