DEV Community

Arif Iqbal
Arif Iqbal

Posted on • Updated on

Regular Expressions in JavaScript - Day 18 of 100

This post is a part of the Week X of 100DaysOfCode JavaScript Challenge series.

  • Match Whitespace:

\s the lowercase s can match white space and white space between other characters. It includes white space, tab, form feed, new line, carriage return and vertical tab. You can consider it equivalent to the character class [\t\n\r\f\v].

var str = "whitespace. whitespace everywhere!";
const regex = /\s/g;

console.log(str.match(regex)); // [" ", " "]
Enter fullscreen mode Exit fullscreen mode
  • Match Non-Whitespace Characters:

\S the uppercase S will match everything but not whitespace. It will not match tab character, newline, form feed, carriage return, and vertical tab. You can consider it an equivalent to the character class [^\t\n\r\f\v].

var str = "whitespace. whitespace everywhere!";
const regex = /\S/g;

console.log(str.match(regex).length); // 32
Enter fullscreen mode Exit fullscreen mode
  • Specify Upper and Lower Number of Matches:

Previously we learned how to match the letter one or more times with the + character and match zero or more times with the asterisk * characters. But sometimes you would want to specify a lower and upper bound number for the match. You do this with the help of the quantity specifier. You specify the upper and lower bound numbers in the curly brackets {}.

let a4 = "aaaah";
let a2 = "aah";
let multipleA = /a{3,5}h/;

console.log(multipleA.test(a4)); // true
console.log(multipleA.test(a2)); // false
Enter fullscreen mode Exit fullscreen mode
  • Specify Only the Lower Number of Matches:

If you specify only the lower bound number in the quantity specifier with the following comma and omit the upper bound number, it will mean a minimum number match.

let a4 = "aaaah";
let a2 = "aah";
let multipleA = /a{3,}h/; // minimum three times

console.log(multipleA.test(a4)); // true
console.log(multipleA.test(a2)); // false
Enter fullscreen mode Exit fullscreen mode
  • Specify Exact Number of Matches:

If you specify only one number in the curly brackets {X}, only that number of times will be matched.

let a4 = "haaaah";
let a2 = "haah";
let a3 = "haaah";
let threeA = /ha{3}h/; // minimum three times

console.log(threeA.test(a4)); // false
console.log(threeA.test(a2)); // false
console.log(threeA.test(a3)); // true
Enter fullscreen mode Exit fullscreen mode
  • Check for All or None:

Previously we used the ? mark to lazy match a string. Another use of this character is to make a character match optional.

console.log(/colou?r/.test("color")); // true
console.log(/colou?r/.test("colour")); // true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)