婷婷同學_
2023-06-15 17:21:08
我正在嘗試從將成為網站標題的字符串中包裝最后三個單詞。我正在嘗試使用 split 方法和 pop 但沒有得到它。 var text = "This is an example text sentence"我想像這樣查看 html 這是一個示例文本句子var split = text.split(" ");var last = split.pop() // but it gives me only the last word text.join(" ") + (text.length > 0 ?' <span class="text-stroke">' + last + "</span>" : last)
2 回答

慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
使用正則表達式匹配\s+\S+(空格,后跟非空格)任意次數,匹配一個單詞,后跟$(字符串的末尾):
var text = "This is an example text sentence"
const newHTML = text.replace(
/(?:\s+\S+){3}$/,
'<span>$&</span>'
);
console.log(newHTML);

互換的青春
TA貢獻1797條經驗 獲得超6個贊
// split your text by spaces
let text = "This is an example text sentence.".split(/\s+/)
// rejoin your text
let nexText = text.slice(0, text.length-3).join(' ')
+ ' <span>'
+ text.slice(text.length-3).join(' ')
+ '</span>'
console.log(nexText)
// => This is an <span>example text sentence.</span>
添加回答
舉報
0/150
提交
取消