Create Excerpt Using Regular Expression

by Tom

I came across this JavaScript regular expression a while ago that uses regular expressions to create excerpts from a larger block of text. You can specify the number of characters in the excerpt by simply changing the second value within the braces in the regular expression. For example use {1,55} to create an excerpt 55 characters long or {1,101} to create an excerpt 101 characters long. Of course the best part is that the phrase will always truncate on a whitespace character!

var s = "This regex can be used to break a long ";
s += "line of text on a full word. The qualifiers ";
s += "specify the minimum and maximum number ";
s+= "of character allow before the  break and can ";
s+= "be changed according to your needs";

var result = s.match(/^([\\s\\S]){1,30}([\\s\\.])/)

document.write(result[0] + " ");

I cannot remember where I got this from, but thought that I would share it with the community as I have found it to be extremely useful.

If you found this helpful or interesting, please share it!

{ 4 comments… read them below or add one }

Raymond Camden

Are you sure about this code? It didn’t seem to work for me.

Jim

Sorry Ray,

Wordpress killed my backslashes! The code above is now correct.

Jim

Anon

sorry code got messed up!

Atomicron

Looking at the regex, it could be rewritten as:

/^(.){30,}?([\s\.,])/

This will match the first white-space, comma, or period after the 30th character.

Leave a Comment

Previous post:

Next post: