JavaScript RegExp Object with Example

Updated on     Kisan Patel

Regular expressions are search patterns that can be used to find text that matches a given pattern.

RegExp can be both a literal and an object. To create a RegExp literal, you use the following syntax.

var re = /regular expression/;

Regular Expression Modifiers

Modifiers can be used to perform case-insensitive more global searches.

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Regular Expression Patterns

Brackets are used to find a range of characters.

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning.

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers define quantities.

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n

The regular expression pattern is contained between opening and closing forward slashes. Note that this pattern is not a string: you do not want to use single or double quotes around the pattern.

For Example, the following is a regular expression for a pattern that matches against a string that contains the word Kisan and the word Patel, in that order, and separated by one or more whitespace characters.

var re = /Kisan\s+Patel/;

The RegExp is a JavaScript object as well as a literal, so it can also be created using a constructor, as follows:

var re = new RegExp("Kisan\s+Patel");

The RegExp test method

var patt = /study/;
patt.test("The string contains study text!"); // return true. sentence contains "study" text.

Use a JavaScript regular expression to define a search pattern, and then apply the pattern against the string to be searched, using the RegExp test method.

The String match method

Use the String match method and a regular expression to validate that a string is a Social Security number.

var ssn = document.getElementById("pattern").value;
var pattern = /^\d{3}-\d{2}-\d{4}$/;
if (ssn.match(pattern))
   alert("OK");
else
   alert("Not OK");

JavaScript

Leave a Reply