Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 15, 2021 07:05 am GMT

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 [
\r\f\v]
.

var str = "whitespace. whitespace everywhere!";const regex = /\s/g;console.log(str.match(regex));

will return [" ", " "].

  • 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 [^
\r\f\v]
.

var str = "whitespace. whitespace everywhere!";const regex = /\S/g;console.log(str.match(regex).length);

will return 32.

  • 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)); // trueconsole.log(multipleA.test(a2)); // false
  • 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 timesconsole.log(multipleA.test(a4)); // trueconsole.log(multipleA.test(a2)); // false
  • 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 timesconsole.log(threeA.test(a4)); // falseconsole.log(threeA.test(a2)); // falseconsole.log(threeA.test(a3)); // true
  • 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")); // trueconsole.log(/colou?r/.test("colour")); // true

Original Link: https://dev.to/arifiqbal/regular-expressions-in-javascript-day-18-of-100-4o2e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To