I'm trying to make a JS function that cuts a string after n characters - that works. The problem is if it's in the middle of a word it looks bad, so I need your help making it cut the whole word if it's the middle of it.
My code so far:
if($('#desc').text().length > 505){
str = $("#desc").text();
$('#desc').text(str.substring(0, 505)).append('...');
}
P.S
- #desc is the div that contains my string.
- you can use jQuery.
You may want to have a look at Cutter.js
This simple function will work in any situation, plus adding 3 dots if needed :
Example:
It's a combination of a
for
loop,charAt
, and a means of testing the character against ones you consider to be word delimiters. I'll use a regular expression for that:Live example | source