简体   繁体   English

如何将字符串/标题中的最后三个单词换行

[英]How to wrap in span last three words from string / heading

I am trying to wrap last three words from string that will be a heading on site.我正在尝试将字符串中的最后三个单词包装起来,这将是网站上的标题。 I am trying with split method and with pop but not getting it.我正在尝试使用 split 方法和 pop 但没有得到它。

 var text = "This is an example text sentence"

i would like to look in html like this This is an 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)

Use a regular expression to match \\s+\\S+ (spaces, followed by non-spaces) as many times as you want to match a word, followed by $ (the end of the string):使用正则表达式匹配\\s+\\S+ (空格,后跟非空格)的次数与您想要匹配的单词相同,后跟$ (字符串的结尾):

 var text = "This is an example text sentence" const newHTML = text.replace( /(?:\\s+\\S+){3}$/, '<span>$&</span>' ); console.log(newHTML);

 // 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM