Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Object Properties JS Object Methods JS Object Display JS Object Constructors JS Events JS Strings JS String Methods JS String Search JS String Templates JS Numbers JS BigInt JS Number Methods JS Number Properties JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iteration JS Array Const JS Dates JS Date Formats JS Date Get Methods JS Date Set Methods JS Math JS Random JS Booleans JS Comparisons JS If Else JS Switch JS Loop For JS Loop For In JS Loop For Of JS Loop While JS Break JS Iterables JS Sets JS Set Methods JS Maps JS Map Methods JS Typeof JS Type Conversion JS Destructuring JS Bitwise JS RegExp JS Precedence JS Errors JS Scope JS Hoisting JS Strict Mode JS this Keyword JS Arrow Function JS Classes JS Modules JS JSON JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words

JS Versions

JS Versions JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS 2019 JS 2020 JS 2021 JS 2022 JS 2023 JS 2024 JS IE / Edge JS History

JS Objects

Object Definitions Object Prototypes Object Methods Object Properties Object Get / Set Object Protection

JS Functions

Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Bind Function Closures

JS Classes

Class Intro Class Inheritance Class Static

JS Async

JS Callbacks JS Asynchronous JS Promises JS Async/Await

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM Forms DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS Web APIs

Web API Intro Web Forms API Web History API Web Storage API Web Worker API Web Fetch API Web Geolocation API

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Graphics

JS Graphics JS Canvas JS Plotly JS Chart.js JS Google Chart JS D3.js

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Interview Prep JS Bootcamp JS Certificate

JS References

JavaScript Objects HTML DOM Objects


JavaScript Regular Expressions


A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.


What Is a Regular Expression?

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.

Syntax

/pattern/modifiers;

Example

/w3schools/i;

Example explained:

/w3schools/i  is a regular expression.

w3schools  is a pattern (to be used in a search).

i  is a modifier (modifies the search to be case-insensitive).


Using String Methods

In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.


Using String search() With a String

The search() method searches a string for a specified value and returns the position of the match:

Example

Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";
let n = text.search("W3Schools");

The result in n will be:

6

Try it Yourself »


Using String search() With a Regular Expression

Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

let text = "Visit W3Schools";
let n = text.search(/w3schools/i);

The result in n will be:

6

Try it Yourself »



Using String replace() With a String

The replace() method replaces a specified value with another value in a string:

let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
Try it Yourself »

Use String replace() With a Regular Expression

Example

Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:

let text = "Visit Microsoft!";
let result = text.replace(/microsoft/i, "W3Schools");

The result in res will be:

Visit W3Schools!
Try it Yourself »

Did You Notice?

Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).


Regular Expression Modifiers

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

Modifier Description Try it
i Perform case-insensitive matching Try it »
g Perform a global match (find all) Try it »
m Perform multiline matching Try it »
d Perform start and end matching (New in ES2022) Try it »

Regular Expression Patterns

Brackets are used to find a range of characters:

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

Metacharacters are characters with a special meaning:

Metacharacter Description Try it
\d Find a digit Try it »
\s Find a whitespace character Try it »
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b Try it »
Try it »
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx Try it »

Quantifiers define quantities:

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

Using the RegExp Object

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.


Using test()

The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

Example

const pattern = /e/;
pattern.test("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:

true

Try it Yourself »

You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:

/e/.test("The best things in life are free!");

Using exec()

The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an object.

If no match is found, it returns an empty (null) object.

The following example searches a string for the character "e":

Example

/e/.exec("The best things in life are free!");
Try it Yourself »

Complete RegExp Reference

For a complete reference, go to our Complete JavaScript RegExp Reference.

The reference contains descriptions and examples of all RegExp properties and methods.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.