This post is a part of the Week X of 100DaysOfCode JavaScript Challenge series.
- Positive and Negative Lookahead:
A positive lookahead /(?=...)/
looks for the presence of the pattern in the string. Negative lookahead /(?!...)/
looks for the absence of the pattern in the string.
console.log("quit".match(/q(?=u)/)); // returns ["q"] because "u" is present after "q"
console.log("qtui".match(/q(?!u)/)); // returns ["q"] because "u" is not present after "q"
- Check For Mixed Grouping of Characters:
Sometimes we want to look for a mixed group of characters, either this or that.
Example 1
let myString = "Eleanor Roosevelt";
let myRegex = /(Eleanor|Franklin).*Roosevelt/g;
let result = myRegex.test(myString);
console.log(result) // true
Example 2
let testStr = "Pumpkin";
let testRegex = /P(engu|umpk)in/;
console.log(testRegex.test(testStr)); // true
- Reuse Patterns Using Capture Groups:
Capture Groups are regex patterns enclosed in parenthesis. For example, \w+
is a regex pattern that matches an alphanumeric word. So the corresponding capture group will /(\w+)/
.
We can reuse these capture groups within the same regex pattern. Capture groups saved in temporary variables. To reuse the capture group, access it by a backslash followed by the number of the capture group. Capture groups are numbered automatically based on the opening parenthesis from left to right.
Example 1
let repeatStr = "row row row your boat";
let repeatRegex = /(\w+) \1 \1/;
console.log(repeatRegex.test(repeatStr)); // Returns true
console.log(repeatStr.match(repeatRegex)); // Returns ["row row row", "row"]
Example 2
let repeatRegex = /(\w+) \1 (\d+) \2/;
let repeatStr = "row row 2211 2211 your boat";
console.log(repeatRegex.test(repeatStr)); // Returns true
console.log(repeatStr.match(repeatRegex)); // Returns ["row row 2211 2211", "row", "2211"]
- Use Capture Groups to Search and Replace:
We can replace a substring inside a string using the replace()
function in the way "some string".replace(/someregex/, "replacement")
. We can use capture groups in the replacement string to conveniently swap the words like in the example below.
console.log("Code Camp".replace(/(\w+)\s(\w+)/, "$2 $1")); // "Camp Code"
- Remove Whitespace from Start and End:
We can remove any whate space characters from the start and end of a string using the trim()
function. But how can remove them using regex? Here is how
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
console.log(result); // returns "Hello, World!"
And the with this the Regular Expressions module of the JavaScript course was completed.
Latest comments (0)