Free Web Development Online Tutorials, Learn to Code
How to use regular expresssion in javascript, javascript regular expresssion example

Javascript Regular Expresssion

JavaScript Regular expressions is a powerful way of doing search and replace in any strings, a regular expression describes a pattern of characters.

Regular expresssion Patterns and flags

Slashes "/" indicate JavaScript that we are starting a regular expression, just like quotes for strings.

var str = "WebTrainingRoom.Com is a eLearning Platform";
var wtrRegExp=/WebTrainingRoom/i

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

Regular Expresssion Brackets

Bracket is used for finding a range of characters:

Expression Description
[xyz] Find any character between the brackets
[^xyz] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9] Find any character NOT between the brackets (any non-digit)
(a|b) Find any of the alternatives specified

Regular Expresssion Methods

Here are two very useful methods of regular expresssion we often use!

Let’s understand regular expression with following examples.

We want to accept only alphanumeric letters in our string, so to validate that we write following expression

var letterNumber = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$/;

Here we split the above string with some explanation that will help you to understand the expression in small parts.

  • ^ indicates start the string
  • $ indicates end the string
  • (?=.*[a-zA-Z]) means the alphabets from a-z, A-Z
  • (?=.*[0-9]) indicates any number from 0-9
  • [A-Za-z0-9] indicates whether everything is either alphabetical or number
  • + means one or more times
  • /string/, we put any expression inside two forward slash

Now to validate any string with above expression we can write code like example below.

let userInputString ="WebTrainingRoom10";
let letterNumber = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$/;

The above code will tell us whether the user input string value is matching the regular expression we have defined, if not, then we can display error message.

You may be interested in following posts

Javascript Regular Expresssion

javascript Interview Questions Answers

JavaScript Examples | JavaScript Online Course