JavaScript Regular Expressions
A regular expression is a pattern that describes text. A program uses the pattern to test whether real text fits the description.
Testing for a digit
The test method reports true when the text matches the pattern. The pattern \d stands for any one digit.
let label = "room 42";
console.log(/\d/.test(label));
console.log(/\d/.test("room"));A word pattern
A plain word in a pattern matches that exact text.
let sentence = "the cat sat";
console.log(/cat/.test(sentence));
console.log(/dog/.test(sentence));Ignoring case
The i flag after the closing slash makes the match ignore letter case.
console.log(/ana/.test("Ana"));
console.log(/ana/i.test("Ana"));Example
let username = "Ana_42";
console.log(/\d/.test(username));
console.log(/ana/i.test(username));
console.log(username.search(/\d/));Key points
- A regular expression describes text with a pattern instead of one exact string.
- A pattern sits between two slash characters, like /cat/.
- The dot in a pattern matches any single character.
- Patterns are their own small language, and this lesson keeps them simple ahead of a later depth pass.
In this example, the pattern \d tests whether the username holds a digit, and the answer is true. The pattern /ana/i then matches the opening letters despite the capital A. The search call reports position 4, the place of the first digit.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does /\d/.test("abc") return?