This code snippet prints "Found a match!"
as a single-digit value (in the range of 0
to 9
) is present in the string. We can combine these square brackets to obtain more interesting results (such as matching consecutive characters) as illustrated below.

[a-z] matches any character between 'a' and 'z', [0-9] matches any character between '0' and '9'. Since they are placed right next to each other, the match is found consecutively.

Here the third part of the expression, [a-z] did not match the third consecutive character of the pattern. As a result, a matching string was not found.
Characters and digits can also be combined for matching, such as in the following example.

Let's see another metacharacter, a period (.
). A period matches any single character occurring at that specific place in a string (except newline character).
The regex 'chips.dip' matches any string which has any single character in-between 'chips' and 'dip', such as the one given in input 'chipsndip' or 'chipsmdip'.
xxxxxxxxxx
// Adding a function to wrap the existing code
function findMatch() {
let s = 'chipsndip';
if (/chips.dip/.test(s)) {
console.log("Found a match!");
} else {
console.log("Did not find a match.");
}
}
// Driver code to execute the function
findMatch();