RegExp object
CSGNetwork FREE Source Code, Javascript Source, and Code Snippets!
CSGNetwork Custom Search
     Bookmark and Share
CSGNetwork
Snippets
Calculators
Top Free Apps
Home
Back



Right click this window and select "view source" in order to copy the source for this script.

RegExp object

Regular expressions are a powerful tool for performing pattern matches in Strings in JavaScript. You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions.

Regular expressions are implemented in JavaScript in two ways:

1) Using literal syntax.
2) When you need to dynamically construct the regular expression, via the RegExp() constructor.

The literal syntax looks something like:

var RegularExpression = /pattern/

while the RegExp() constructor method looks like

var RegularExpression  =  new RegExp("pattern");

The RegExp() method allows you to dynamically construct the search pattern as a string, and is useful when the pattern is not known ahead of time.

For a complete tutorial and reference on Regular Expressions in JavaScript, please refer to the following:

Introduction

Validating user input is the bane of every software developer’s existence. When you are developing cross-browser web applications (IE4+ and NS4+) this task becomes even less enjoyable due to the lack of useful intrinsic validation functions in JavaScript. Fortunately, JavaScript 1.2+ has incorporated regular expressions. In this article I will present a brief tutorial on the basics of regular expressions and then give some examples of how they can be used to simplify data validation.

Regular Expressions and Patterns

Regular expressions are very powerful tools for performing pattern matches. PERL programmers and UNIX shell programmers have enjoyed the benefits of regular expressions for years. Once you master the pattern language, most validation tasks become trivial. You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions.

So how are regular expressions implemented in JavaScript? There are two ways:

1) Using literal syntax.
2) When you need to dynamically construct the regular expression, via the RegExp() constructor.

The literal syntax looks something like:

var RegularExpression = /pattern/

while the RegExp() constructor method looks like

var RegularExpression  =  new RegExp("pattern");

The RegExp() method allows you to dynamically construct the search pattern as a string, and is useful when the pattern is not known ahead of time.

To use regular expressions to validate a string you need to define a pattern string that represents the search criteria, then use a relevant string method to denote the action (ie: search, replace etc). Patterns are defined using string literal characters and metacharacters. For example, the following regular expression determines whether a string contains a valid 5-digit US postal code (for sake or simplicity, other possibilities are not considered):

<script language="JavaScript1.2">
function checkpostal(){
var re5digit=/^\d{5}$/ //regular expression defining a 5 digit number
if (document.myform.myinput.value.search(re5digit)==-1) //if match failed
alert("Please enter a valid 5 digit number inside form")
}
</script>

<form name="myform">
<input type="text" name="myinput" size=15>
<input type="button" onClick="checkpostal()" value="check">

</form>
Example (check input for 5 digit number): 

Lets deconstruct the regular expression used, which checks that a string contains a valid 5-digit number, and ONLY a 5-digit number:

var re5digit=/^\d{5}$/
  • ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning.
  • \d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters.
  • $ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string.

Translated to English, this pattern states: "Starting at the beginning of the string there must be nothing other than 5 digits. There must also be nothing following those 5 digits."

Now that you've got a taste of what regular expressions is all about, lets formally look at its syntax, so you can create complex expressions that validate virtually anything you want.

What is a regular expression?

Regular expressions is a form of pattern matching that you can apply on textual content. Take for example the DOS wildcards ? and * which you can use when you're searching for a file. That is a kind of very limited subset of RegExp. For instance, if you want to find all files beginning with "fn", followed by 1 to 4 random characters, and ending with "ht.txt", you can't do that with the usual DOS wildcards. RegExp, on the other hand, could handle that and much more complicated patterns.

Regular expressions are, in short, a way to effectively handle data, search and replace strings, and provide extended string handling. Often a regular expression can in itself provide string handling that other functionalities such as the built-in string methods and properties can only do if you use them in a complicated function or loop.

RegExp Syntax

There are two ways of defining regular expressions in JavaScript — one through an object constructor and one through a literal. The object can be changed at runtime, but the literal is compiled at load of the script, and provides better performance. The literal is the best to use with known regular expressions, while the constructor is better for dynamically constructed regular expressions such as those from user input. In almost all cases you can use either way to define a regular expression, and they will be handled in exactly the same way no matter how you declare them.

Declaration

Here are the ways to declare a regular expression in JavaScript. While other languages such as PHP or VBScript use other delimiters, in JavaScript you use forward slash (/) when you declare RegExp literals.

Syntax Example
RegExp Literal
/pattern/flags; var re = /mac/i;
RegExp Object Constructor
new RegExp("pattern","flags"); var re = new RegExp(window.prompt("Please input a regex.","yes|yeah"),"g");

Flags

There are three flags that you may use on a RegExp. The multiline flag is supported only in JavaScript1.5+, but the other two are supported in pretty much every browser that can handle RegExp (JavaScript.1.2+). These flags can be used in any order or combination, and are an integral part of the RegExp.

Flag Description
Global Search
g The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.
Ignore Case
i The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters such as Ś, Ł, Ů, ś.
Multiline Input
m This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively. JavaScript1.5+ only.


Bookmark and Share
Registered® Trademark™ and Copyright© 1973 - CSG, Computer Support Group, Inc. and CSGNetwork.Com All Rights Reserved