Rickkwa
Rickkwa

Reputation: 2291

Truncate string to keep the first n words

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.

Upvotes: 3

Views: 1093

Answers (3)

Rickkwa
Rickkwa

Reputation: 2291

This code truncates the text to keep the first n words, while keeping the rest of the text unchanged.

For example, you want to restrict users from typing/pasting too many words of text; you don't want to be changing what they typed aside from truncating.

var words = text.split(/(?=\s)/gi);
var indexToStop = words.length;
var count = 0;
for (var i = 0; i < words.length && count <= n; i++) {
    if (words[i].trim() != "") {
        if (++count > n)
            indexToStop = i;
    }
}
var truncated = words.slice(0, indexToStop).join('');

Upvotes: 0

Timur Osadchiy
Timur Osadchiy

Reputation: 6219

First replace redundant spaces with one space:

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

Upvotes: 4

Amit Joki
Amit Joki

Reputation: 59252

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('');

Upvotes: 7

Related Questions