Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string to keep the first n words

Tags:

javascript

As the title says, I'm trying to truncate a string to the first n words.

var text = $("#textarea-id").val();
var truncated = text.split(/(?=\s)/gi).slice(0, n).join('');

This gets me what I want, but the problem is that if there are two whitespace characters in a row, then it counts one of the whitespace characters as its own word. How can I prevent that without altering the string (aside from the truncation)?

I've tried using the + quantifier after the \s in the regular expression but that doesn't do anything.

like image 510
Rickkwa Avatar asked Jan 29 '26 03:01

Rickkwa


1 Answers

Simply replace more than 1 space with just a single space before splitting.

var truncated = text.replace(/\s+/g," ").split(/(?=\s)/gi).slice(0, n).join('');
like image 75
Amit Joki Avatar answered Jan 30 '26 16:01

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!