- JavaScript Basics
- JavaScript Tutorial
- JavaScript: where to write
- JavaScript: how to display
- JavaScript: keywords
- JavaScript: comments
- JavaScript: variables
- JavaScript: operators
- JavaScript: data types
- JavaScript Conditional Statements
- JavaScript: if-else
- JavaScript: switch
- JavaScript: for loop
- JavaScript: while loop
- JavaScript: do-while loop
- JavaScript: break and continue
- JavaScript Popup Boxes
- JavaScript: alert box
- JavaScript: confirm box
- JavaScript: prompt box
- JavaScript Popular Topics
- JavaScript: functions
- JavaScript: innerHTML
- JavaScript: getElementById()
- JavaScript: getElementsByClassName()
- JavaScript: getElementsByName()
- JavaScript: getElementsByTagName()
- JavaScript: querySelector()
- JavaScript: querySelectorAll()
- JavaScript: document.write()
- JavaScript: console.log()
- JavaScript: boolean
- JavaScript: events
- JavaScript: Math object
- JavaScript: Math.random()
- JavaScript: Number()
- JavaScript: parseInt()
- JavaScript: parseFloat()
- JavaScript Arrays
- JavaScript: array
- JavaScript: find length of array
- JavaScript: add element at beginning
- JavaScript: add element at end
- JavaScript: remove first element
- JavaScript: remove last element
- JavaScript: get first index
- JavaScript: get last index
- JavaScript: reverse an array
- JavaScript: sort an array
- JavaScript: concatenate arrays
- JavaScript: join()
- JavaScript: toString()
- JavaScript: from()
- JavaScript: check if value exists
- JavaScript: check if array
- JavaScript: slice an array
- JavaScript: splice()
- JavaScript: find()
- JavaScript: findIndex()
- JavaScript: entries()
- JavaScript: every()
- JavaScript: fill()
- JavaScript: filter()
- JavaScript: forEach()
- JavaScript: map()
- JavaScript Strings
- JavaScript: string
- JavaScript: length of string
- JavaScript: convert to lowercase
- JavaScript: convert to uppercase
- JavaScript: string concatenation
- JavaScript: search()
- JavaScript: indexOf()
- JavaScript: search() vs. indexOf()
- JavaScript: match()
- JavaScript: match() vs. search()
- JavaScript: replace()
- JavaScript: toString()
- JavaScript: String()
- JavaScript: includes()
- JavaScript: substr()
- JavaScript: slice string
- JavaScript: charAt()
- JavaScript: repeat()
- JavaScript: split()
- JavaScript: charCodeAt()
- JavaScript: fromCharCode()
- JavaScript: startsWith()
- JavaScript: endsWith()
- JavaScript: trim()
- JavaScript: lastIndexOf()
- JavaScript Date and Time
- JavaScript: date and time
- JavaScript: Date()
- JavaScript: getFullYear()
- JavaScript: getMonth()
- JavaScript: getDate()
- JavaScript: getDay()
- JavaScript: getHours()
- JavaScript: getMinutes()
- JavaScript: getSeconds()
- JavaScript: getMilliseconds()
- JavaScript: getTime()
- JavaScript: getUTCFullYear()
- JavaScript: getUTCMonth()
- JavaScript: getUTCDate()
- JavaScript: getUTCDay()
- JavaScript: getUTCHours()
- JavaScript: getUTCMinutes()
- JavaScript: getUTCSeconds()
- JavaScript: getUTCMilliseconds()
- JavaScript: toDateString()
- JavaScript: toLocaleDateString()
- JavaScript: toLocaleTimeString()
- JavaScript: toLocaleString()
- JavaScript: toUTCString()
- JavaScript: getTimezoneOffset()
- JavaScript: toISOString()
- JavaScript Regular Expression
- JavaScript: regular expression
- JavaScript: RegEx . (dot)
- JavaScript: RegEx \w and \W
- JavaScript: RegEx \d and \D
- JavaScript: RegEx \s and \S
- JavaScript: RegEx \b and \B
- JavaScript: RegEx \0
- JavaScript: RegEx \n
- JavaScript: RegEx \xxx
- JavaScript: RegEx \xdd
- JavaScript: RegEx quantifiers
- JavaScript: RegEx test()
- JavaScript: RegEx lastIndex
- JavaScript: RegEx source
- JavaScript Programs
- JavaScript Programs
JavaScript Regular Expression (RegEx) with example programs
This post is published to provide complete information about regular expressions in JavaScript.
What is a regular expression?
A regular expression is something like a sequence of characters. But it is not a normal sequence of characters; rather, it is a sequence that forms a search pattern.
Sometimes, we need to implement a simple or complex search in our application, where the search is based on some pattern. For example, let us suppose we are going to implement a form that asks some information about the user, like:
- password
- contact numbers
- and many more.
where we need to match the pattern of this data before feeding it into the database. For example, if we take the first piece of data, that is, email, then we need to match the user's email properly. For example, an email must start with a unique username like codescracker followed by @ and a company URL like gmail.com, hotmail.com, etc.
So these are some of the scenarios where regular expressions come into play, which allow us to implement the match pattern for any data we need to match. But before starting the match pattern, we need to understand its modifiers and patterns. So let's get started.
JavaScript Regular Expression Syntax
Whatever the pattern or regular expression you use for matching, the basic and general form you need to follow is:
/pattern/modifiers;
Here, pattern refers to the search pattern that is used to match. For example:
<!DOCTYPE html> <html> <body> <p>The first 'is' is available at Index no.<span id="xyz"></span></p> <script> let myString = "JavaScript is Fun, is not it?"; let pos = myString.search(/is/); document.getElementById("xyz").innerHTML = pos; </script> </body> </html>
The first 'is' is available at Index no.
Note: The search() method is used to search a substring (value) in a string using a regular expression.
And modifiers are used to change the default search method. For example:
<!DOCTYPE html> <html> <body> <p>The first 'is' available at Index no.<span id="xyz"></span></p> <script> let myString = "JavaScript Is Fun. Is not it?"; let pos = myString.search(/is/i); document.getElementById("xyz").innerHTML = pos; </script> </body> </html>
The first 'is' available at Index no.
The i after /is/ forces the search pattern to be case-insensitive.
JavaScript Regular Expression Flags or Modifiers
Flags or modifiers in regular expressions are used to modify the search method. Here is the list of flags that can be used in JavaScript regular expressions:
- g: used to force the search pattern to go for all matches
- i: used to force the search pattern to go case-insensitive matching
- m: used to force the match pattern to go multiline
For example, let me create a JavaScript example without using any modifiers. Then we will use modifiers to see the change:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let myString = "JavaScript is Fun, is not it?"; let matches = myString.match(/is/); document.getElementById("xyz").innerHTML = matches; </script> </body> </html>
Note: The match() method is used to match a string with or using a regular expression.
Now let me implement the g modifier to allow the match pattern globally. That is, to get all matches instead of stopping after the first match:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let myString = "JavaScript is Fun, is not it?"; let matches = myString.match(/is/g); document.getElementById("xyz").innerHTML = matches; </script> </body> </html>
Then let's use the i modifier to do case-insensitive matching:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let myString = "JavaScript is Fun. Is not it?"; let matches = myString.match(/is/gi); document.getElementById("xyz").innerHTML = matches; </script> </body> </html>
JavaScript Regular Expression Patterns
In JavaScript regular expressions, we can use brackets to apply the match pattern through the range of characters defined in the brackets. For example:
- [abc]: matches any of the enclosed characters. That is, this pattern can be used to match any characters that are in the brackets. We can also use [a-c].
- [^abc]: matches any character except the enclosed characters. We can also use [^a-c].
- [0-9]: matches any of the enclosed numbers.
- [^0-9]: matches any character except the enclosed characters.
- (a|b): matches any of the characters.
For example:
<!DOCTYPE html> <html> <body> <p>List of all Matches for First Pattern: <b><span id="resA"></span></b></p> <p>List of all Matches for Second Pattern: <b><span id="resB"></span></b></p> <p>List of all Matches for Third Pattern: <b><span id="resC"></span></b></p> <script> let text = "WE have created codescracker.com to provide FREE online learning."; let a = text.match(/[re]/gi); let b = text.match(/[^re]/gi); let c = text.match(/[a-d]/gi); document.getElementById("resA").innerHTML = a; document.getElementById("resB").innerHTML = b; document.getElementById("resC").innerHTML = c; </script> </body> </html>
List of all Matches for First Pattern:
List of all Matches for Second Pattern:
List of all Matches for Third Pattern:
Let me create another example that uses the [0-9] and [^0-9] patterns:
<!DOCTYPE html> <html> <body> <p>List of all Matches for First Pattern: <b><span id="A"></span></b></p> <p>List of all Matches for Second Pattern: <b><span id="B"></span></b></p> <p>List of all Matches for Third Pattern: <b><span id="C"></span></b></p> <script> let text = "X23sx495682043-234932lo6023"; let a = text.match(/[0-9]/g); let b = text.match(/[^0-9]/g); let c = text.match(/[3-6]/g); document.getElementById("A").innerHTML = a; document.getElementById("B").innerHTML = b; document.getElementById("C").innerHTML = c; </script> </body> </html>
List of all Matches for First Pattern:
List of all Matches for Second Pattern:
List of all Matches for Third Pattern:
Here is another example regarding the (a|b) pattern:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let mystr = "What do you like? Cricket or Football?"; let ptrn = /(cricket|football)/gi; document.getElementById("xyz").innerHTML = mystr.match(ptrn); </script> </body> </html>
It is not limited to using only two characters or words. We can use multiple words or characters to match the listed characters or words. For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let mystr = "London, Berlin, london, Austin, Dallas, Seattle"; let ptrn = /(London|Austin|Dallas|Berlin)/gi; document.getElementById("xyz").innerHTML = mystr.match(ptrn); </script> </body> </html>
List of Metacharacters Used in JavaScript Regular Expressions
Metacharacters are characters that start with a backslash (/) followed by character(s) that have special meaning in computer programming and play an important role in defining the match pattern while working with regular expressions in JavaScript.
Here is the list of metacharacters used in JavaScript regular expressions:
- . is used to match any character (except newline and/or other line terminators).
- \w is used to match all word characters. A-Z, a-z, 0-9, and underscore (_) are all word characters.
- \W is used to match all characters except word characters.
- \d is used to match any digit from 0 to 9.
- \D is used to match any character other than digits (0-9).
- \s is used to match any whitespace. A space, tab, vertical tab, new line, carriage return, and form feed are all whitespaces.
- \S is used to match any character other than whitespace characters.
- \b is used to match any word beginning or ending with specified character or combination of characters.
- \B is used to match any word that does not begin or end with a specified character or combination of characters.
- \0 is used to find a null character.
- \n is used to match a new line in the specified string.
- \f is used to match the form feed character. Since it is exactly similar to matching a new line character. Therefore, I have not created a separate article on it..
- \r is used to match carriage return characters. It is also similar to \n
- \t is used to match the tab character. Similar to \n
- \v is used to match vertical tab characters. Similar to \n
- \xxx is used to match a character using its octal number, in the form xxx. For example, 165, which is equal to 'u'
- \xdd is used to match a character using its hexadecimal number, in the form xdd. For example, 75, which is equal to 'u'
Quantifiers in JavaScript regular expressions are described in a separate post.
« Previous Tutorial Next Tutorial »