我使用这个脚本来选择容器中的第一个单词:
$(".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个第一个单词?
谢谢
你可以这样做。
$(".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(" ");
});
编辑:根据评论。
试试这个......你可以从你的段落中获得前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>