• Skip to content

Menu 1

  • Home
  • Work
  • Small Worlds
  • Play
  • Blog
  • Podcasts
  • Newsletter
  • About

Thomas
Beutel

Kinetic sculpture · prints · small worlds · stories
  • Home
  • Work
  • Small Worlds
  • Play
  • Blog
  • Podcasts
  • Newsletter
  • About
AuthorPostedbyThomason June 17, 2011

Get the first N words with Javascript

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 …

♡

Posted in Uncategorized

1 Comment

  1. kk
    12 years ago Permalink

    Too good

Comments are closed.

Post navigation

Previous
Next
© 2026 Thomas Beutel Instagram · YouTube · SoundCloud
x