如何在单词周围添加 span 元素

How to add span element around the word

本文关键字:添加 span 元素 单词周      更新时间:2023-09-26

如何使用jQuery在标题的最后一个单词周围添加span元素。

我想要这样的输出:

<div class="hedererty">
  <h1>Lorem ipsum dolor sit amet, consectetuer adipiscing <span>elit</span></h1>
</div>

注意:这是示例标题。在我的网站标题随着不同的页面而变化。

有什么想法或建议吗?谢谢。

尝试

$('.hedererty h1').html(function(idx, html){
    return html.replace(/('w+)$/, '<span>$1</span>')
})

演示:小提琴

$('.hedererty h1').html(function (idx, html) {
    return html.replace(/('s['S]+)$/, '<span>$1</span>')
})

演示:小提琴

split()字符串,将

span添加到弹出的字符串中,并使用join()连接字符串

$(".hedererty h1").html(function(){
    var mystring= $(this).text().split(" "); //Split the string
    var lastword = mystring.pop(); //Pop the last index value
    return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword); 
    //Return concatenated string
});

演示