Reputation: 9
I would like to limit a number of words in a div with jQuery to make my Website title look better.
I already tried the solution below but unfortunately it cut the words in half what it’s rubbish.
<div class="entry-title">Auxerunt haec vulgi sordidioris audaciam, quod cum ingravesceret penuria commeatuum</div>
$(document).ready(function(){
$(".entry-title").text(function(index, currentText) {
return currentText.substr(0, 20);
});
});
This one count the character I would like one that counts the words.
Thanks for the Help.
Upvotes: 0
Views: 1037
Reputation: 35670
split()
the text into an array of n words, then join()
them.
$(".entry-title").text(function(index, currentText) {
return currentText
.split(' ', 4) //create array of the first four words
.join(' '); //join the array with spaces
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-title">Auxerunt haec vulgi sordidioris audaciam, quod cum ingravesceret penuria commeatuum</div>
Upvotes: 3