A regular expression is a range of characters forming a pattern that can be searched in a string which is usually used for validation, for example, for validating credit card numbers or for replacing matched text with another string. Moreover, it also has great multiple language support-learn it once and you can use it across many programming languages.
The advantages that REGEX offers may put this function in limelight, but not many developers are interested in using REGEX, in fact, not few people who take a first look at regex, and ignore it completely. Therefore, few developers and web developers can surmount the complexity of REGEX. However, if one can manage to use it, it will produce you with better and faster searching results.
If you get used to JavaScript, you still need to learn all the characters, classes, quantifiers, modifiers, and methods used in regex.
Let’s see a simple example with an explanation. This is a regex.
B[a-zA-Z\d]+
The above regex will look like this in a line, a character ‘B’ followed by at least one of any character between (and including) ‘a’ to ‘z’, ‘A’, to ‘Z’ and numbers 0 to 9.
Here’s a sample of matches in a line highlighted:
Basket, bulb, B12 vitamin, BaS04, N BC company
The above regex will stop the search at
Basket
And return a positive response. That’s because the global modifier ‘g’ has to be specified if you want the regex to look into all the possible matches.
Below are several ways on how to use this expression in JavaScript. The method goes: if found a match return true, else false.
1
2 3 4 5 |
var input = “your test string”, regex = /B[a-zA-Z\d]+/;
if(!regex.test(input)) alert(‘No match is found’); else alert(‘A match is found’); |
Let’s try another method: match returns the matches found in an array.
input = “your test string”,
regex = /B[a-zA-Z\d]+/g,
/*I’ve added the global modifier ‘g’ to the regex to get all the matches*/
ary = input.match(regex);
if(ary===null)
alert(‘No match is found’);
else
alert(‘matches are: ‘ + ary.toString());
How about string replace? Let’s try that with regex now.
1
2 3 |
var input = “your test string”,
regex = /B[a-zA-Z\d]+/g; alert(input.replace(regex, “#”)); |