Get the first N words with Javascript

by Thomas Beutel

Here’s how I get the first 20 words using a regular expression and the Javascript replace function. I place an ellipsis at the end to indicate that the sentence was shortened:


var str1 = "Here is a sentence that just seems to go on and on. Here is a sentence that just seems to go on and on. Here is a sentence that just seems to go on and on.";
var str2 = str1.replace(/(([^\s]+\s\s*){20})(.*)/,"$1…");
document.write(str2);
// result:
// Here is a sentence that just seems to go on and on. Here is a sentence that just seems to …