1. Technology

JavaScript By Example

Objects: 8. RegExp


In a similar way to how the Math object extends what you can do with numbers, RegExp objects extend what you can do with strings by adding the abiliity to match and replace based on patterns rather than specific text.

One of the biggest advantages to using regular expressions is that once you learn how they work for one programming language you almost know how to use them in a dozen or so more languages as well since with only minor differences they work the same way in all the different languages that support them.

Regular expressions work by assigning special meanings to a number of characters that can be escaped using \ to restore their normal meaning as well as some characters that can be escaped using \ to give them a special meaning. Presumably this was worked out so as to reduce the situations where characters need to be escaped.

Like with objects and arrays, regular expressions also have a shortcut way of defining them but unlike the others there are things you can do with the long version of a regular expression object that cannot be done with the short version.

Note that when using the long version of the RegExp object definition you need to escape all the \ you are using as the regular text escape characters are applied first to the text string before passing it to the RegExp object.

Here we have two examples. The first shows the long version of the RegExp object matching entered text on word boundaries so as to find out if a given class name appears within a class attribute. The second shows the short version being used to strip leading and trailing whitespace from a text string.

document.getElementsByClassName = function(cl) {
var myclass, elem, classes, retnode;
retnode = [];
myclass = new RegExp('\\b'+cl+'\\b');
elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
return retnode;

String.prototype.trim = function() {
var re;
re = /^\s*(.*?)\s*$/;
return this.replace(re,"$1");}

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Objects
  7. JavaScript By Example - Objects: RegExp

©2014 About.com. All rights reserved.