JavaScript

Javascript Regular Expressions Example

Regular expressions are patterns used to match character combinations in strings. They are used to perform pattern-matching and “search-and-replace” functions on text. In JavaScript, regular expressions are also objects.

JavaScript’s regular expression flavor is part of the ECMA-262 standard for the language. This means your regular expressions should work exactly the same in all implementations of JavaScript. In the past there were many serious browser-specific issues. But modern browsers do a very good job of following the JavaScript standard for regular expressions. You only need to make sure your web pages have a doctype that requests the browser to use standards mode rather than quirks mode.
 

1. Document Setup & Introduction

The following section helps you prepare the file where we’re going to code and introduce you to the very basic syntax and application of regular expressions. We’ll have a more detailed look at each of the ways we can use these expressions later in this article.

1.1 Document Setup

First, create a new HTML document with the basic syntax inside, including an empty (for now) script section:

js-regexp.html

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Regular Expressions Example</title>
</head>
<body>

<!-- HTML SECTION  -->

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">

</script>

</body>
</html>

In the HTML section, let’s also add few lines we’ll need for more interactive results:

<!-- HTML SECTION  -->
<p>Click the button to perform something with regular expressions.</p>
<button onclick="resultFunction()">See Result</button>
<p id="result"></p>

1.2 Syntax & Application

The syntax of a regular expression is as follows: /pattern/modifiers;

For example: var patt = /webcodegeeks/i where:

  • /webcodegeeks/i is a regular expression.
  • webcodegeeks is a pattern (to be used in a search).
  • i is a modifier (modifies the search to be case-insensitive).

1.3 Creating a regular expression

You construct a regular expression in one of two ways:

Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

var re = /ab+c/;

Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.

Or calling the constructor function of the RegExp object, as follows:

var re = new RegExp("ab+c");

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and are getting it from another source, such as user input.

2. Types of Regular Expressions

Regular expressions can be divided in six groups of similar expressions.

2.1 Modifiers

Modifiers are used to perform case-insensitive and global searches:

i – Does a case-insensitive search for “webcodegeeks” in a string:

<script type="text/javascript">
function resultFunction() {
    var str = "Refer to WebCodeGeeks";  
    var patt1 = /webcodegeeks/i;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

i - Perform case-insensitive matching
i – Perform case-insensitive matching

g – Performs a global match (find all matches rather than stopping after the first match:

<script type="text/javascript">
function resultFunction() {
    var str = "This is not what it is!";
    var patt1 = /is/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

g - Perform a global match
g – Perform a global match

m – Performs multi line matching. In this case we’re trying to get all “is” in the beginning of the line.

<script type="text/javascript">
function resultFunction() {
    var str = "\nWhat is this? \nIs it a cookie?";
    var patt1 = /is/m;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

m - Perform multiline matching
m – Perform multiline matching

2.2 Brackets

Brackets are used to find a range of characters:

[abc] – Finds any character between the brackets.

<script type="text/javascript">
function resultFunction() {
    var str = "Why are you still here?";
    var patt1 = /[y]/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

[abc] - Find any character between the brackets
[abc] – Find any character between the brackets
[^abc] – Finds any character NOT between the brackets.

<script type="text/javascript">
function resultFunction() {
    var str = "Why are you still here?";
    var patt1 = /[^y]/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

[^abc] - Find any character NOT between the brackets
[^abc] – Find any character NOT between the brackets
[0-9] – Finds any digit between the brackets.

<script type="text/javascript">
function resultFunction() {
    var str = "123456789";
    var patt1 = /[2-5]/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

[0-9] - Find any digit between the brackets
[0-9] – Find any digit between the brackets
(x|y) – Finds any of the alternatives specified.

<script type="text/javascript">
function resultFunction() {
    var str = "web code geeks we code world wide";
    var patt1 = /(code|web)/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

(x|y) - Find any of the alternatives specified
(x|y) – Find any of the alternatives specified

2.3 Metacharacters

Metacharacters are characters with a special meaning:

. – Finds a single character, except newline or line terminator.

<script type="text/javascript">
function resultFunction() {
    var str = "That's my hot hat!";
    var patt1 = /(h.t)/g;    // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

. - Find a single character, except newline or line terminator
. – Find a single character, except newline or line terminator

\w – Finds a word character.

<script type="text/javascript">
function resultFunction() {
    var str = "Interest raised to 4.5%";
    var patt1 = /\w/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\w - Find a word character
\w – Find a word character

\W – Finds a NON word character.

<script type="text/javascript">
function resultFunction() {
    var str = "Interest raised to 4.5%";
    var patt1 = /\W/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\W - Find a non-word character
\W – Find a non-word character

As you can see, all spaces, the comma and the percentage character are shown, because they are considered non-word.

\d – Finds a digit.

<script type="text/javascript">
function resultFunction() {
    var str = "I'm 114 years old!";
    var patt1 = /\d/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\d - Find a non-word character
\d – Find a non-word character

\D – Finds a non-digit character.

<script type="text/javascript">
function resultFunction() {
    var str = "I'm 114 years old!";
    var patt1 = /\D/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\D - Find a non-digit character
\D – Find a non-digit character

\s – Finds a whitespace character.

<script type="text/javascript">
function resultFunction() {
    var str = "There is not much to show here";
    var patt1 = /\s/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\s - Find a whitespace character
\s – Find a whitespace character

\S – Finds a non-whitespace character.

<script type="text/javascript">
function resultFunction() {
    var str = "There is not much to show here";
    var patt1 = /\S/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\S - Find a non-whitespace character
\S – Find a non-whitespace character

\b – Finds a match at the beginning/end of a word.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG - WebCodeGeeks";
    var patt1 = /\bWCG/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\b - Find a match at the beginning/end of a word
\b – Find a match at the beginning/end of a word

\B – Finds a match not at the beginning/end of a word.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG - WebCodeGeeks";
    var patt1 = /\BCode/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\B - Find a match not at the beginning/end of a word
\B – Find a match not at the beginning/end of a word

\0 – Finds a NUL character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG.\0Learn JAVA";
    var patt1 = /\0/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\0 - Find a NUL character
\0 – Find a NUL character

\n – Finds a new line character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WebCodeGeeks. \nLearn JAVA";
    var patt1 = /\n/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\n - Find a new line character
\n – Find a new line character

\f – Finds a form feed character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG. Learn\f HTML";
    var patt1 = /\f/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\f - Find a form feed character
\f – Find a form feed character

\r – Finds a carriage return character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit\r WCG. Learn jQuery.";
    var patt1 = /\r/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\r - Find a carriage return character
\r – Find a carriage return character

\t – Finds a tab character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG. Learn CSS3 \tfor free.";
    var patt1 = /\t/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\t - Find a tab character
\t – Find a tab character

\v – Finds a vertical tab character.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WCG. Learn \vAngularJS.";
    var patt1 = /\v/;   // pattern/modifier
    var result = str.search(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\v - Find a vertical tab character
\v – Find a vertical tab character

\xxx – Finds the character specified by an octal number xxx.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WebCodeGeeks. Learn programming.";
    var patt1 = /\127/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\xxx - Find the character specified by an octal number xxx
\xxx – Find the character specified by an octal number xxx

\xdd – Finds the character specified by a hexadecimal number dd.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WebCodeGeeks. Learn programming.";
    var patt1 = /\x57/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\xdd - Find the character specified by a hexadecimal number dd
\xdd – Find the character specified by a hexadecimal number dd

\uxxxx – Finds the Unicode character specified by a hexadecimal number xxxx.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WebCodeGeeks. Learn programming.";
    var patt1 = /\u0057/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

\uxxxx - Find the Unicode character specified by a hexadecimal number xxxx
\uxxxx – Find the Unicode character specified by a hexadecimal number xxxx

2.4 Quantifiers

n+ – Matches any string that contains at least one n.

<script type="text/javascript">
function resultFunction() {
    var str = "Visit WebCodeGeeks. Learn programming.";
    var patt1 = /\u0057/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n+ - Matches any string that contains at least one n
n+ – Matches any string that contains at least one n

n* – Matches any string that contains zero or more occurrences of n.

<script type="text/javascript">
function resultFunction() {
    var str = "Hello Lory";
    var patt1 = /lo*/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n* - Matches any string that contains zero or more occurrences of 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.

<script type="text/javascript">
function resultFunction() {
    var str = "1, 100 or 1000?";
    var patt1 = /10?/g;   // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n? - Matches any string that contains zero or one occurrences of n
n? – Matches any string that contains zero or one occurrences of n

n{X} – Matches any string that contains a sequence of X n’s.

<script type="text/javascript">
function resultFunction() {
    var str = "100, 1000 or 10000?";
    var patt1 = /\d{4}/g;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n{X} - Matches any string that contains a sequence of X n's
n{X} – Matches any string that contains a sequence of X n’s

n{X,Y} – Matches any string that contains a sequence of X to Y n’s.

<script type="text/javascript">
function resultFunction() {
    var str = "100, 1000 or 10000?";
    var patt1 = /\d{4}/g;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n{X,Y} - Matches any string that contains a sequence of X to Y n's
n{X,Y} – Matches any string that contains a sequence of X to Y n’s

n{X,} – Matches any string that contains a sequence of at least X n’s.

<script type="text/javascript">
function resultFunction() {
    var str = "100, 10 or 10000?";
    var patt1 = /\d{3,}/g;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n{X,} - Matches any string that contains a sequence of at least X n's
n{X,} – Matches any string that contains a sequence of at least X n’s

n$ – Matches any string with n at the end of it.

<script type="text/javascript">
function resultFunction() {
    var str = "Is this his";
    var patt1 = /is$/g;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

n$ - Matches any string with n at the end of it
n$ – Matches any string with n at the end of it

^n – Matches any string with n at the beginning of it.

<script type="text/javascript">
function resultFunction() {
    var str = "Is this his";
    var patt1 = /^Is/g;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

^n - Matches any string with n at the beginning of it
^n – Matches any string with n at the beginning of it

?=n – Matches any string that is followed by a specific string n.

<script type="text/javascript">
function resultFunction() {
    var str = "Is this all there is";
    var patt1 = /is(?= all)/;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

?=n - Matches any string that is followed by a specific string n
?=n – Matches any string that is followed by a specific string n

?!n – Matches any string that is not followed by a specific string n.

<script type="text/javascript">
function resultFunction() {
    var str = "Is this all there is";
    var patt1 = /is(?! all)/gi;  // pattern/modifier
    var result = str.match(patt1);  // result from matching
    document.getElementById("result").innerHTML = result; // set result to the paragraph
}
</script>

The result after clicking the button which will trigger the paragraph text to be added, would be (in blue):

?!n - Matches any string that is not followed by a specific string n
?!n – Matches any string that is not followed by a specific string n

3. RegExp Object

3.1 RegExp Object Properties

  • constructor – returns the function that created the RegExp object’s prototype
  • global – checks whether the “g” modifier is set
  • ignoreCase – checks whether the “i” modifier is set
  • lastIndex – specifies the index at which to start the next match
  • multiline – checks whether the “m” modifier is set
  • source – returns the text of the RegExp pattern

3.2 RegExp Object Methods

  • compile() – deprecated in version 1.5. Compiles a regular expression
  • exec() – tests for a match in a string. Returns the first match
  • test() – tests for a match in a string. Returns true or false
  • toString() – returns the string value of the regular expression

4. Conclusion

To conclude, a regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.

5. Download the source code

Download
You can download the full source code of this example here: Javascript Regular Expression

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Martin
Martin
8 years ago

Thanks for the article.

The first example under “2.4 Quantifiers” was copy-pasted from the previous and has a wrong pattern.

Back to top button