javascript - 如何使用 jQuery 在 span 标签中包装文本,除了第一个单词?

标签 javascript html

是否可以使用 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/

相关文章:

javascript - 使用 js 与 Time 进行数学运算

javascript - 如何将类应用于 div 的第一个按钮?

javascript - 尝试将ajax添加到rails应用程序以刷新注释,但js文件未在浏览器中执行

html - 项目符号列表未在 blogdown .rmd 文件中呈现

html - 让 PDF 保留在嵌入的 <object> 或 &lt;iframe&gt; 中

html - 纯 CSS Accordion 在 CSS 选项卡中不起作用

javascript - 编辑视频按钮

javascript - 具有多个条件的 Mongoose "Find"

html - 如何在 css 中模糊我的背景图像?

javascript - 如何使用 JQuery 删除 HTML 字符串中的所有 "script"标记?