The data toolbox

INPUT · Slides

Testing text patterns

01 / 05

Verifying text shapes

In input forms, you often need to check inputs: "digits only", "3 digits followed by 4 digits", or "letters only".

Checking character by character with loops is tedious. Regular Expressions (RegExp) give you a clean way to match text patterns.

02 / 05

Enclosing patterns in /

Regular expressions are written between slashes: /pattern/.

Key symbols:

  • ^: Start of the string
  • $: End of the string
  • \d: Any digit (0-9)
  • +: Preceding element repeats 1 or more times

For example, /^\d+$/ means "from start to end, only digits, with at least one digit".

const pattern = /^\d+$/;console.log(pattern.test("12345"));console.log(pattern.test("12a45"));

Result

true
false

03 / 05

Testing matches with .test()

The .test(str) method of a regular expression returns true if the string matches, and false otherwise.

Because it returns a boolean, it slots right into if conditions.

const isNumber = /^\d+$/;const input = "980";if (isNumber.test(input)) {  console.log("is a number");}

Result

is a number

04 / 05

Specifying character sets and lengths

You can specify character sets and lengths:

  • [a-z]: Any lowercase letter
  • [A-Z]: Any uppercase letter
  • {3}: Exactly 3 characters
  • {3,8}: Between 3 and 8 characters

For instance, /^\d{3}-\d{4}$/ matches standard postal code formats.

const zipPattern = /^\d{3}-\d{4}$/;console.log(zipPattern.test("123-4567"));console.log(zipPattern.test("1234567"));

Result

true
false

05 / 05

Check the key points

Let us review the ideas:

  • /pattern/ creates a RegExp
  • ^ matches start, $ matches end
  • \d matches digits, [a-z] matches lowercase letters
  • + matches 1+, {n} matches n characters
  • .test(str) returns a boolean match result

Let us practice testing patterns!