1. Home
  2. Computing & Technology
  3. JavaScript

Regular Expressions

17. Lookahead

clr gif

Lookahead means being able to examine what follows a particular pattern within our regular expression without actually including that following text in the pattern itself. There are two variants of lookahead processing that allow us to either test for the following text matching a particular pattern or alternatively for the following text to not match a particular pattern.

Lookaheads allow you to test what comes next in the text string without changing the current position being tested within the text. In addition, lookaheads are not captured in the backreference array.

var re = /\b(.+(?=work\b))/;

This regular expression will look for words that end in "work" and will capture the prefix in the backreference array. For example "homework" would save "home", "schoolwork" would save "school" etc.

var re = /\b(c\w+(?!ment))/;

This regular expression will look for words that start with "c" and do not contain "ment". This expression would therefore match "contain" and "create" for example and these words would be added to the backreference array. It would not match such words as "commenting" or "containment" and so these words would not be added to the backreference array.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.