How to Use regex in Javascript
Learn how to use regex in javascript with examples.
What is RegEx
It is a built-in object, used to define a search pattern (or regular expression), which can be used to make a wide variety of tests on a given string. RegEx is also called a regular expression. There are two different ways in which we can define/create regular expressions in javascript:
- Using RegExp object constructor notation
- RegExp literal notation.
Using RegExp object constructor notation
Syntax:
var variablename = new RegExp("search pattern", ['"flags"]);
Ex: phone number validation:
var pattern = new RegExp["^[0-9]{10}$");
Using RegExp literal noatioan:
Syntax:
var variablename =/search pattern/[flags];
Ex: phone number validation:
var pattern = /^[0-9]{10}$/;
Basic Methods
test() Method: It is used to test if is there a match or no match between a regular expression and the given string. If there is a match then it returns true otherwise returns false.
syntax:
pattern.test(str:String):Boolean
Ex:
var ph = "1234567890";
var pattern =/^[0-9]{10}$/;
document.write(pattern.test(ph)); //true
Application of RegExp
- Search for a word in a given string
- Find & replace a word in a string
- perform data validations, etc.