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.
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('');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With