Regular Expression
Understanding The Basic Of RegExp In JavaScript

I am a web developer with so much passion for solving problems and writing ๐๐. I love watching movies and playing chess a lot. I am that simple guy๐. Byeeee
Regular Expressions Often shortened as Regex or Regexp are patterns that help programmers to search, match and replace texts. They're powerful but can be hard to read because they make us of special characters.
Using The Test Method
Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching. If you want to find the word the in the string Maxwell is a handsome boy, you could use the following regular expression: /handsome/. Notice that quote marks are not required within the regular expression. rather the "/... / " marks JavaScript has multiple ways to use regexes. One way to test a regex is using the .test() method. The .test() method takes the regex, applies it to a string (which is placed inside the parentheses), and returns true or false if your pattern finds something or not.
let regex = 'Maxwell is a handsome boy';
let wordSearch = /handsome/;
wordSearch.test(regex);
console.log(wordSearch.test(regex)); // True
Output is meant to return either "True" or "False", Output of the console:- True
Match Literal Strings
In the last example, we searched for the word Handsome using the regular expression /Handsome/. That regex searched for a literal match of the string Handsome. Here's another example searching for a literal match of the string Bayo:
let testStr = "Hello, my name is Bayo.";
let testRegex = /Bayo/;
testRegex.test(testStr); //True
This test call will return True.
Any other forms of Bayo will not match. For example, the regex /Bayo/ will not match bayo or BAYO.
let wrongRegex = /bayo/;
wrongRegex.test(testStr); //False
This test call will return False.
This isn't the end of the show. I will show you how to match those other forms as well.
Match A Literal String With Different Possibilities
Using regexes like /reading/, you can look for the pattern coding in another string. This is powerful to search single strings, but it's limited to only one pattern. You can search for multiple patterns using the alternation or OR operator: "|". This operator matches patterns either before or after it. For example, if you wanted to match the strings yes or no, the regex you want is /yes|no/. You can also search for more than just two patterns. You can do this by adding more patterns with more OR operators separating them, like /yes|no|maybe/. example:- Match the regex myThings to toy, boy, coy, poy
let myString = 'The woman have a toy'
let myRegex = /boy|toy|coy|poy/
let outcome = myRegex.test(myString) //True
Output:- True
Ignore Case While Matching
Regex is case sensitive, How do you deal with case differences when it is case sensitive. Case (or sometimes letter case) is the difference between uppercase letters and lowercase letters. Examples of uppercase are A, B, and C. Examples of lowercase are a, b, and c. You can match both cases using what is called a flag. There are other flags but here you'll focus on the flag that ignores case - the i flag. You can use it by appending it to the regex. An example of using this flag is /ignorecase/i. This regex can match the strings ignorecase, igNoreCase, and IgnoreCase. example:- Write a Regex to match javaScript without case sensitivity.
let strRegex = 'I love javaScript';
let findRegex = /javascript/i;
let outcome = findRegex.test(strRegex); //True
Output:- True
Extract Matches
So far, we have only been checking if a word or several words exist using the .test() method. We haven't been able to extract such words as the output. You can do that using the .match() method. To use the .match() method, apply the method on a string and pass in the regex inside the parentheses. example:-
let words = 'Hello World';
let strRegex = /Hello/
let outcome = words.match(strRegex);
Note : The .match syntax is the "opposite" of the .test method you have been using thus far:
strRegex.test(words); //True
words.match(strRegex); //Hello
- Output1:- True
- Output2:- 'Hello';
Find More Than the First Match Passed
How do you extract a particular repeated word in Regex. This can be done using the /g flag example:-
let testStr = "Love, Love, Love";
let ourRegex = /Love/;
testStr.match(ourRegex); //Love
Output:- 'Love'
But with using the g flag it will be
let testStr = "Love, Love, Love";
let ourRegex = /Love/g;
testStr.match(ourRegex); // Love, Love, Love
Output:- 'Love, Love, Love';
Note:- You can have multiple flags on your regex like /search/gi
Match Anything with Wildcard Period
Sometimes you won't (or don't need to) know the exact characters in your patterns. Thinking of all words that match, say, a misspelling would take a long time. Luckily, you can save time using the wildcard character: "." The wildcard character "." will match any one character. The wildcard is also called dot and period. You can use the wildcard character just like any other character in the regex. For example, if you wanted to match can, man, tan, and ran, you can use the regex /an./ to match all four words. example:-
let talent = "I can sing alot";
let strRegex = /an./;
huRegex.test(humStr); //True
Output:- True
Match Single Character with Multiple Possibilities
We've all learnt how to match literal characters /word/ and wildcat characters /./ You can search for a literal pattern with some flexibility with character classes. Character classes allow you to define a group of characters you wish to match by placing them inside square [ and ] brackets. For example, you want to match bag, big, and bug but not bog. You can create the regex /b[aiu]g/ to do this. The [aiu] is the character class that will only match the characters a, i, or u. example:- Use regex vowelRegex to find all the vowel sounds in the string quoteSample
let quoteSample = "I have always had the great passion for coding ever since i was a kid.";
let vowelRegex = /[aeiou]/gi;
let result = quoteSample.match(vowelRegex);
console.log(result) Output:- All the vowel sounds in the string
Match Letters Of The Alphabet Passed
You saw how you can use character sets to specify a group of characters to match, but that's a lot of typing when you need to match a large range of characters (for example, every letter in the alphabet). Fortunately, there is a built-in feature that makes this short and simple. Inside a character set, you can define a range of characters to match using a hyphen character: -. For example, to match lowercase letters a through e you would use [a-e]. example:-
let myWords = "I know i shall make it one day";
let alphabetRegex = /[a-z]/gi;
let result = myWords.match(alphabetRegex);
console.log(result.length)
Output:- 23 because all letters of the string were being matched and the length determined.
Match Numbers And Letters Of The Alphabet Passed
Using the hyphen "-" to match a range of characters is not limited to letters. It also works to match a range of numbers. For example, /[0-5]/ matches any number between 0 and 5, including the 0 and 5. Also, it is possible to combine a range of letters and numbers in a single character set. example:-
let myCodes = "Maxeto20011213";
let myRegex = /[a-z0-9]/gi;
let outcome = myCodes.match(myRegex);
console.log(outcome)
Output:- [ 'M', 'a', 'x', 'e', 't', 'o', '2', '0', '0', '1', '1', '2', '1', '3' ]
Match Single Characters Not Specified
So far, We have created a set of characters that we want to match, but we could also create a set of characters that we do not want to match. These types of character sets are called negated character sets. To create a negated character set, you place a caret character "^" after the opening bracket and before the characters we do not want to match. example:-
let myHabit = 'Drinking 2 ice-teas';
let strRegex = /[aeiou0-9]/gi;
let outcome = myHabit.match(strRegex);
console.log(outcome.length);
Output:- 7
Match Characters that Occur One or More Times
How can you match characters or group of characters that occur more than once in a row. This can be made possible through the + symbol. It matched repeated characters that occur more than once in a row example:- /a+/g would find one match in abc and return ["a"]. Because of the +, it would also find a single match in aabc and return ["aa"]. If it were instead checking the string abab, it would find two matches and return ["a", "a"] because the a characters are not in a row - there is a b between them. Finally, since there is no a in the string bcd, it wouldn't find a match. example:-
let difficultSpelling = "Mississippi";
let myRegex = /ss+/gi;
let result = difficultSpelling.match(myRegex);
console.log(result);
Output:- ['ss', 'ss']
Match Characters That Occur Zero Or More Times
In the last lesson, we made use of + to match characters that appeared more than once in a row. But how about characters that occur zero or more times. We make use of the "*" sign
Match Beginning String Patterns
Prior challenge shown that the negated regex can be used to match characters that you don't want to match. The caret ^ can also be used to search for the patterns at the beginning of a string. example:-
let string = 'Emily loves to sing';
let strRegex = /^E/;
let syCase = /^loves/;
let result = strRegex.test(string);
let outcome = syCase.test(string);
console.log(result); // true
console.log(outcome); // false
Match Ending String Patterns
In the last challenge we learnt how to match starting patterns of strings. There is also a way we can search for the end pattern of a string. This can be done by using the dollar sign $ at the end of the regex. example:-
let string = 'Emily loves to sing';
let strRegex = /g$/;
let syCase = /E$/;
let result = strRegex.test(string);
let outcome = syCase.test(string);
console.log(result); // true
console.log(outcome); // false
Match All Letters And Numbers
Using character classes, you were able to search for all letters of the alphabet with [a-z].This kind of character class is common enough that there is a shortcut for it, although it includes a few extra characters as well. The closest character class in JavaScript to match the alphabet is \w. This shortcut is equal to [A-Za-z0-9_]. This character class matches upper and lowercase letters plus numbers. Note, this character class also includes the underscore character _ example:-
let words = 'I know i shall make it';
let strRegex = /\w/gi;
let result = words.match(strRegex);
console.log(result.length) // 17
Comparatively:-
let words = 'I know i shall make it';
let strRegex = /\w+/gi;
let result = words.match(strRegex);
console.log(result.length); // 6
Match Everything But Letters and Numbers
You've learned that you can use a shortcut to match alphanumerics [A-Za-z0-9_] using \w. A natural pattern you might want to search for is the opposite of alphanumerics. You can search for the opposite of the \w with \W. Note, the opposite pattern uses a capital letter. This shortcut is the same as [^A-Za-z0-9_]. example:-
let quoteSample = "The five boxing wizards jump quickly.";
let nonAlphabetRegex = /\W/gi;
let result = quoteSample.match(nonAlphabetRegex).length;
console.log(result); // 6
Match All Numbers
You've learned shortcuts for common string patterns like alphanumerics. Another common pattern is looking for just digits or numbers.The shortcut to look for digit characters is \d, with a lowercase d. This is equal to the character class [0-9], which looks for a single character of any number between zero and nine.
Match All Non-Numbers
The last challenge showed how to search for digits using the shortcut \d with a lowercase d. You can also search for non-digits using a similar shortcut that uses an uppercase D instead. The shortcut to look for non-digit characters is \D. This is equal to the character class [^0-9], which looks for a single character that is not a number between zero and nine.
Match Whitespace
Whitespaces are spaces between letters. You can search for whitespace using \s, which is a lowercase s. This pattern not only matches whitespace, but also carriage return, tab, form feed, and new line characters. You can think of it as similar to the character class [ \r\t\f\n\v].** example:-
let string = "I have been made to conquer";
let countWhiteSpace = /\s/g;
let result = string.match(countWhiteSpace);
console.log(result) // [ ' ', ' ', ' ', ' ', ' ' ]
Match Non-Whitespace Characters
You learned about searching for whitespace using \s, with a lowercase s.You can also search for everything except whitespace. Search for non-whitespace using \S ,which is an uppercase s. This pattern will not match whitespace, carriage return, tab, form feed, and new line characters. You can think of it being similar to the character class [^ \r\t\f\n\v].
example:-
let str = "Looking for the bigger picture";
let countNonWhiteSpace = /\S/g;
let outcome = str.match(countNonWhiteSpace);
console.log(outcome.length) // 26
The regex /\S/g is equivalent to /\w/g
Specify Upper and Lower Number of Matches
Recall that you use the plus sign + to look for one or more characters and the asterisk "*" to look for zero or more characters. These are convenient but sometimes you want to match a certain range of patterns. You can specify the lower and upper number of patterns with quantity specifiers. Quantity specifiers are used with curly brackets ({ and }). You put two numbers between the curly brackets - for the lower and upper number of patterns. For example, to match only the letter a appearing between 3 and 5 times in the string ah, your regex would be /a{3,5}h/. example:-
let str = 'Argggghhhh';
let string = 'Arghhh';
let regex = /Arg{3,10}h/gi
let result = regex.test(str);
let outcome = string.test(regex);
console.log(result) // true
console.log(outcome) // false
Specify Only the Lower Number of Matches
You can specify the lower and upper number of patterns with quantity specifiers using curly brackets {number, }. Sometimes you only want to specify the lower number of patterns with no upper limit. To only specify the lower number of patterns, keep the first number followed by a comma. example:-
let words = 'Commmmp';
let str = 'commp';
let regex = /com{3,}p/gi;
let result = regex.test(words);
let outcome = regex.test(str);
console.log(result) // true
console.log(outcome) // false
This implies that the string must have m at least 3 times
Specify Exact Number of Matches
You can specify the lower and upper number of patterns with quantity specifiers using curly brackets. Sometimes you only want a specific number of matches. To specify a certain number of patterns, just have that one number between the curly brackets{number}. example:- Let the exact number of 'w' in a string be exactly 4. if true output true and if false output false
let word = 'Maxwwwwell';
let str = 'maxwwwel';
let regex = /maxw{4}ell/gi;
let result = regex.test(word);
let outcome = regex.test(str);
console.log(result); // true
console.log(outcome); // false
Check for All or None
Sometimes the patterns you want to search for may have parts of it that may or may not exist. However, it may be important to check for them nonetheless. You can specify the possible existence of an element with a question mark ?. This checks for zero or one of the preceding element. You can think of this symbol as saying the previous element is optional. For example, there are slight differences in American and British English and you can use the question mark to match both spellings. example:-
let amStr = 'flavor';
let word = /flavou?r/;
let outcome = word.test(str);
console.log(outcome); // true
Positive and Negative Lookahead
Lookaheads are patterns that tell JavaScript to look-ahead in your string to check for patterns further along. This can be useful when you want to search for multiple patterns over the same string. There are two kinds of lookaheads: positive lookahead and negative lookahead. A positive lookahead will look to make sure the element in the search pattern is there, but won't actually match it. A positive lookahead is used as (?=...) where the ... is the required part that is not matched. On the other hand, a negative lookahead will look to make sure the element in the search pattern is not there. A negative lookahead is used as (?!...) where the ... is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present. example:- Lookaheads are a bit confusing but some examples will help.
let quit = "qu";
let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex);
noquit.match(qRegex);
// Both of these match calls would return ["q"].
A more practical use of lookaheads is to check two or more patterns in one string. Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number:
let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password);
Check For Mixed Grouping of Characters
Sometimes we want to check for groups of characters using a Regular Expression and to achieve that we use parentheses () If you want to find either Penguin or Pumpkin in a string, you can use the following Regular Expression: /P(engu|umpk)in/g Then check whether the desired string groups are in the test string by using the test() method. example:-
let testStr = "Pumpkin";
let testRegex = /P(engu|umpk)in/;
testRegex.test(testStr);
// The test method here would return true.
Reuse Patterns Using Capture Groups
Some patterns you search for will occur multiple times in a string. It is wasteful to manually repeat that regex. There is a better way to specify when you have multiple repeat substrings in your string. You can search for repeat substrings using capture groups. Parentheses, ( and ), are used to find repeat substrings. You put the regex of the pattern that will repeat in between the parentheses. To specify where that repeat string will appear, you use a backslash \ and then a number. This number starts at 1 and increases with each additional capture group you use. An example would be \1 to match the first group. The example below matches any word that occurs twice separated by a space:
let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr);
repeatStr.match(repeatRegex);
// The test call would return true, and the match call would return ["regex regex", "regex"].
Use Capture Groups to Search and Replace
Searching is useful. However, you can make searching even more powerful when it also changes (or replaces) the text you match. You can search and replace text in a string using .replace() on a string. The inputs for .replace() is first the regex pattern you want to search for. The second parameter is the string to replace the match or a function to do something. example:-
let str = "You are strong.";
let compRegex = /strong/;
str.replace(compRegex, "fine");
// The replace call would return the string You are fine.
Note:- You can also access capture groups in the replacement string with dollar signs $ example:-
let str = 'mango banana orange';
let strRegex = /(\w+)\s(\w+)\s(\w+)/gi
let replaceStr = '$3 $2 $1';
let result = str.replace(strRegex, replaceStr);
console.log(result); // orange banana mango
Reference: freecodecamp
