javascript - Truncate string to keep the first n words - Stack Overflow

admin2025-04-19  1

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.

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.

Share Improve this question asked Mar 5, 2015 at 14:44 RickkwaRickkwa 2,2915 gold badges25 silver badges36 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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

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

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('');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745002369a279308.html

最新回复(0)