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
JavaScript regular expresssion modifiers
  • 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 and Methods

Bracket is used for finding a range of characters:

  • [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!

str.search(reg)
              
str.match(reg)

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]+$/;
userInputString.match(letterNumber);

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 programming tutorials to learn JavaScript coding step by step, develop website using JavaScript and html.
Advanced JavaScript
Javascript Regular Expresssion
javascript Interview Questions Answers
JavaScript Examples | JavaScript Online Course