亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將字符串/標題中的最后三個單詞換行

如何將字符串/標題中的最后三個單詞換行

婷婷同學_ 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);


查看完整回答
反對 回復 2023-06-15
?
互換的青春

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>


查看完整回答
反對 回復 2023-06-15
  • 2 回答
  • 0 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號