I have jotted down a quick post on a Basic JavaScript RegEx Example to give beginners out there a taste of the power of using Regex in jQuery/JavaScript.

Example: Want to extract the price, could be an integer or float from a dataset of prices.



Regex pattern:


You can use a Regular Expression tool such as the Firefox Add-on: Regular Expressions Tester.


As you can see in tool, the matched expression is highlighted blue

Square brackets may be used to define a set of characters that may match. For example, the following regular expression will match any digit from 1 to 5 inclusive.

[12345]     // Matches "1" and "3", but not "a" or "12"

Ranges of numbers and letters may also be specified.

[1-5]       // Same as the previous example 
[a-z]       // Matches any lowercase letter (from the English alphabet)
[0-9a-zA-Z] // Matches any letter or digit

By putting a ^ immediately following the opening square bracket, you can invert the set of characters, meaning the set will match any character not listed:

[^a-zA-Z]   // Matches anything except a letter

The characters ?, +, and * also have special meanings. Specifically, ? means “the preceding character is optional”, + means “one or more of the previous character”, and * means “zero or more of the previous character”.

bana?na     // Matches "banana" and "banna", 
            // but not "banaana". 
bana+na     // Matches "banana" and "banaana", 
            // but not "banna". 
bana*na     // Matches "banna", "banana", and "banaaana", 
            // but not "bnana". 
^[a-zA-Z]+$ // Matches any string of one or more 
            // letters and nothing else.

Parentheses may be used to group strings together to apply ?, +, or * to them as a whole.

ba(na)+na   // Matches "banana" and "banananana", 
            // but not "bana" or "banaana".

Parentheses also let you define several strings that may match, using the pipe (|) character to separate them.

^(ba|na)+$  // Matches "banana", "nababa", "baba", 
            // "nana", "ba", "na", and others.

Here are a few special codes that can be used for matching characters in regular expressions:

.       // Any character except a newline 
\n      // A newline character 
\r      // A carriage return character 
\t      // A tab character 
\b      // A word boundary (the start or end of a word) 
\B      // Anything but a word boundary 
\d      // Any digit (same as [0-9]) 
\D      // Anything but a digit (same as [^0-9]) 
\s      // Single whitespace (space, tab, newline, etc.) 
\S      // Single nonwhitespace 
\w      // A "word character" (same as [A-Za-z0-9_]) 
\W      // A "nonword character" (same as [^A-Za-z0-9_])

Notice that in contrast to the special characters we looked at previously, some (like those above) need to be escaped with a backslash in order to be treated as special codes.

There are more special codes and syntax tricks for regular expressions, all of which should be covered in any complete reference. For now, we have more than enough for our purposes.

Simple JavaScript RegEx Example

function checkPhoneNumber(phoneNo) {
  var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/; 
  if (phoneNo.match(phoneRE)) {
    return true; 
  } else {
    alert( "The phone number entered is invalid!" );
    return false;

Summing It Up

Regular expressions are an invaluable tool for verifying user input. By taking advantage of support for regular expressions in JavaScript, that verification can be done as the data is entered, providing a smoother user experience (Note: server-side validation is still necessary for security, and also to caters for situations where JavaScript is unavailable.) Hope you have enjoyed this Basic JavaScript RegEx Examples.

*This blog post was first published here: Sitepoint.com


About The Author

Related Posts

Leave a Reply

Your email address will not be published.