Regular Expressions In JavaScript

In my first post regarding Regular Expressions (regex), we discussed the basic syntax of regex, its importance and how they are used along with a few examples. I strongly recommend reading that post first if you are completely unfamiliar with regex. Otherwise, lets move on.

This tutorial will not cover what regex are, what are their benefits and the basic syntax. For that refer to my previous post. But this tutorial will

  • Give a very brief introduction to regex
  • The JavaScript syntax
  • The regex modifiers or flags
  • The JS regex methods
  • Some string methods that use regex and
  • Finally some examples

What are they?

Regular Expressions use combinations of special characters to detect patterns in a string. They are widely used in pattern matching and “search and replace” functions on text. With wide support over number of platforms and almost all modern programming languages, it is the natural choice when it comes to string manipulations. Though, at start, its confusing and takes time to master; but once you’re familiar with it, the most daunting tasks could easily be solved with a  small expression.

The most common and easy to articulate use of regex in JS is its use in form validation. For example, users are provided with a signup form on your website and you’re expecting a phone number in the correct format, but that can’t be guaranteed, so you need to do explicit validation before accepting and persisting that phone number in database. For that, you might write a script to check every character to ensure that all the numbers are where they belong with parenthesis and dashes and all sorts of things. This would be pretty tedious bit of code to write. And the telephone number is a very simple case, what if you had to validate an email address or, worse yet, a URL?

Regular expression come here for you rescue. They provide quick and easy way of matching string to a pattern. We will explore more about this in the sections below.

How do they look like?

Regular Expressions look fairly complex at time. But when they are read character by character, they themselves are text strings after all. For example, this is a regex that searches for text “JavaScript” (without quotes) in any given string.

JavaScript

But the bad news is that, most of the times they are not that simple. But that’s why you’re here and I’ll teach you how can you master them through a series of tutorials.Nerd smile

JavaScript Syntax

There are two ways to create regex in JS.

  • Using literal syntax
    var regex = /pattern/modifiers
  • Using RegExp() constructor
    var regex = new RegExp(‘pattern’, ‘modifiers’);

Pattern specifies the pattern of the regular expression
Modifiers specify if the search should be case-sensitive or global etc. For more details you can read the modifiers section of the previous post.

The only difference between the two is that RegExp() is useful when the pattern is not known ahead of time.

JavaScript Methods

The RegExp object provides two methods for working with regex.

  • test()

    It takes one string argument. It searches or tests the string for a specific pattern, returns true if found otherwise returns false.

    var patt1=new RegExp("be");
    alert(patt1.test("The best things in life are free"));
    

    returns true

    var patt1=new RegExp("be ");
    alert(patt1.test("The best things in life are free"));
    

    returns false

  • exec()

    It also takes one string argument. It searches a string for a value, if found, returns an array of matched string and updates the properties of regular expression objet, otherwise returns null. The first element of the returned array contains the entire text matched by the pattern and the subsequent elements contain text matched by capturing groups or capturing parenthesis.

    If you are executing a match simply to find true or false, use the test() method or the String search() (will be discussed later) method.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</a>>
    
    <html>
    <head>
     <title>Javascript Regular Expression Exec()</title>
      <script type="text/javascript">
    var strText = 'If you have noticed this notice you will have noticed that this notice is not  worth noticing';
      var patt = new RegExp("(notice)","gi");
      </script>
    </head>
    <body>
    
     <script type="text/javascript">
     var arr = null;
     // Keep looping over the target text while we can
     // find matches. If no matches can be found,
     // arr is null and will end the while loop.
     while (arr = patt.exec( strText )){
     document.write(
     arr[ 1 ].toUpperCase() +
     "<br />....Start Index: "+arr.index+
     "<br />....End Index: "+patt.lastIndex+
     "<br />....Matched String: "+arr.input.substring(arr.index,patt.lastIndex)+
     "<br /><br />"
     );
     }
      </script>
    
    </body>
    </html>
    

result is

NOTICE
….Start Index: 12
….End Index: 18
….Matched String: notice
NOTICE
….Start Index: 25
….End Index: 31
….Matched String: notice
NOTICE
….Start Index: 46
….End Index: 52
….Matched String: notice
NOTICE
….Start Index: 64
….End Index: 70
….Matched String: notice

The String Methods That Use Regular Expression

String object of JS also offers a few methods to manipulate strings using regular expressions.

Match()

Matches pattern against the input string. It takes on argument, a pattern. Returns each substring that matches the pattern. All matches are returned only if global search g is turned on otherwise return only the first match. If there is no match, it returns null.

var str = "The rain in SPAIN stays mainly in the plain";
var n = str.match(/ain/g);
alert(n); // alerts ain,ain,ain

Search()

Searches the input string for a given pattern. If a match is found returns the index of the start of the match otherwise, returns –1.

var str = "The rain in SPAIN stays mainly in the plain";
var n = str.search(/ain/);
alert(n); // alerts the first index of the matched substring which is 5

Replace()

Performs a search and replace on the given string. Whenever a match is found, it is replaced by replacement string. Returns the new replaced string or same string if no match is found.

var str = "The rain in SPAIN stays mainly in the plain";
var n = str.replace(/ain/,'xxx');
alert(n); // alerts “The rxxx in SPAIN stays mainly in the plain” (without quotes)

or when global search is switched on

var str = "The rain in SPAIN stays mainly in the plain";
var n = str.replace(/ain/g,'xxx');
alert(n); // alerts “The rxxx in SPAIN stays mxxxly in the plxxx” (without quotes)

Split()

Splits the provided string on a pattern and returns an array.The optional limit sets the limit on number of splits.

var str = "The rain in SPAIN stays mainly in the plain";
var n = str.split(/ain/);
alert(n); // Returns an array containing “The r”, “in”, “SPAIN stays m”,”ly in the pl”

Published by

Ali

Some day I'll fill this up. Till then Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo ....

Leave a Reply

Your email address will not be published. Required fields are marked *