Reputation: 217
I use this script to select the 1st word in a container:
$(".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(" ");
});
How can I select the 2 or 3 first words?
Thank you
Upvotes: 0
Views: 79
Reputation: 18873
You can do this way.
$(".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(" ");
});
Edit: As per comments.
Upvotes: 2
Reputation: 1156
try this.. you can get First n Words From your paragraph
$('.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>
Upvotes: 1