JavaScript Regular expressions is a powerful way of doing search and replace in any strings, a regular expression describes a pattern of characters.
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
Bracket is used for finding a range of characters:
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 slashNow 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