选择html标记中的2个第一个单词并添加选择器

问题描述 投票:0回答:2

我使用这个脚本来选择容器中的第一个单词:

$(".article-title").html(function(){
    var text= $(this).text().trim().split(" ");
    var first = text.shift();
    return (text.length > 0 ? "<span class='special'>"+ first + "</span> " : first) + text.join(" ");
});

如何选择2或3个第一个单词?

谢谢

jquery
2个回答
2
投票

你可以这样做。

$(".article-title").html(function(){
    var text= $(this).text().trim().split(" "); //.split() returns an array.
    var first = text[0];
    var second = text[1];
    return (text.length > 0 ? "<span class='special'>"+ first + " " + second + "</span>" : first) + text.slice(2).join(" ");
});

编辑:根据评论。

Working Fiddle


1
投票

试试这个......你可以从你的段落中获得前n个单词

$('.article-title').html(function (i, html) {
    return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
});
<div class="article-title"> this is: a title of the article</div> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.