Skip to main content

JavaScript Regular Expressions

JavaScript Regex Characters

Written by Published

Character classes match a kind of character rather than a specific one.

\d matches any digit, \w any word character.

Square brackets let you define your own set.

Example

Example

javascript

console.log(/\d/.test("abc1"));
console.log(/\d/.test("abc"));

The output is true then false.

The Common Classes

\d a digit, \D anything but a digit.

\w a letter, digit or underscore; \W the opposite.

\s whitespace; . any character at all.

Syntax

Syntax

javascript

/\d/    // a digit
/[aeiou]/  // any of these

Capital letters invert the class.

Your Own Set

Square brackets match any one of the characters inside.

Example

Example

javascript

console.log(/[aeiou]/.test("sky"));
console.log(/[aeiou]/.test("sun"));

The output is false then true.

Ranges

A dash inside brackets makes a range.

Example

Example

javascript

console.log(/[a-z]/.test("ABC"));
console.log(/[A-Z]/.test("ABC"));
console.log(/[0-9]/.test("42"));

[0-9] and \d mean the same thing.

Excluding Characters

A caret at the start of the brackets inverts the set.

Example

Example

javascript

console.log(/[^0-9]/.test("123"));
console.log(/[^0-9]/.test("12a"));

The second is true because of the letter.

The Dot

A dot matches almost any character.

To match a literal dot, escape it with a backslash.

Example

Example

javascript

console.log(/c.t/.test("cat"));
console.log(/c.t/.test("cut"));
console.log(/file\.txt/.test("file.txt"));

Without the backslash, file.txt would also match fileXtxt.

Whitespace

\s covers spaces, tabs and newlines.

Example

Example

javascript

console.log(/\s/.test("no_spaces"));
console.log(/\s/.test("has space"));
console.log("a b".replace(/\s/g, "-"));

Replacing whitespace is a common tidying step.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Regex Characters</title>
</head>
<body>

  <h1>Regex Characters</h1>

  <p id="out"></p>

  <script>
    const text = "Room 42b";

    document.getElementById("out").innerHTML =
      "Has a digit: " + /\d/.test(text) +
      "<br>Digits found: " + text.match(/\d/g).join("") +
      "<br>Has whitespace: " + /\s/.test(text) +
      "<br>Vowels: " + text.match(/[aeiou]/gi).join(", ");
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try excluding:

Search for /[^0-9]/g and see what comes back.

Important Points

  • \d matches a digit and \w a word character.
  • \s matches whitespace.
  • Square brackets define your own set.
  • A caret at the start inverts the set.
  • A dot matches any character; escape it to match a real dot.

Conclusion

Character classes are the vocabulary of regular expressions.

Most patterns are built from these few symbols.

Escaping the dot is the mistake almost everyone makes once.