Skip to content
Advertisement

Shorten text after 50 characters but only after the current word

I need to shorten text after 50 characters but if the 50th char is at the middle of a word – cut only after the word and not before.

example text: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars)

expected output: Contrary to popular belief, Lorem Ipsum is not simply (54 chars)

I was trying this: text.substr(0,50).lastIndexOf(‘ ‘)); – not good for me cause it cuts of the “simply” and I want the simply to be at the shorten text. Thanks for the help!

Advertisement

Answer

Regular expression can help you with it.
The idea is to find at least 50 symbols that finishes with word boundary b

let text = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortetedText = text.match(/.{50,}?(?=b)/)[0];
console.log(shortetedText);

UPD:
If you want to create a function that shorten your text if it’s longer than 50 symbols we can create a function that do it instead of you.

let short = text => text.length > 50 ? text.match(/.{50,}?(?=b)/)[0]: text;  

Then just use it like that:

let longText = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortText = 'Lorem ipsum';
console.log(short(longText)); //will shorten text
console.log(short(shortText)); //will leave text as it is bcoz it's shorter than 50 symbols
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement