The challenges so far have covered matching letters of the alphabet and numbers. You can also match the whitespace or 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].
Ex:
let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s/;
let result = sample.match(countWhiteSpace);
console.log(result); will display [ ' ', ' ', ' ', ' ', ' ' ]
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.
Ex:
let sample = "Whitespace is important in separating words";
let countNonWhiteSpace = /\S/g; //
let result = sample.match(countNonWhiteSpace);
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, here we changed the regex ohRegex to match the entire phrase Oh no only when it has 3 to 6 letter h's.
let ohStr = "Ohhh no";
let ohRegex = /Oh{3,6}\sno/;
let result = ohRegex.test(ohStr);
console.log(result); will display true
Specify Only the Lower Number of Matches
To only specify the lower number of patterns, keep the first number followed by a comma.
For example, here we changed the regex haRegex to match the word Hazzah only when it has four or more letter z's.
let haStr = "Hazzzzzah";
let haRegex = /Haz{4,}ah/;
let result = haRegex.test(haStr)
console.log(result); will display true
Specify Exact Number of Matches
To specify a certain number of patterns, just have that one number between the curly brackets.
For example, here we changed the regex timRegex to match the word Timber only when it has four letter m's.
let timStr = "Timmmmber";
let timRegex = /Tim{4}ber/;
let result = timRegex.test(timStr);
console.log(result); will display true
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)