Borislav Hadzhiev
Fri Nov 19 2021·2 min read
Photo by Alexander Popov
Use the test()
method to check if a regular expression matches an entire
string, e.g. /^hello$/.test(str)
. The caret ^
and dollar sign $
match the
beginning and end of the string. The test
method returns true
if the regex
matches the entire string, and false
otherwise.
const str = 'hello'; const test = /^hello$/.test(str); console.log(test); // 👉️ true const match = str.match(/^hello$/); console.log(match); // 👉️ ['hello']
We used the RegExp.test method to check if a regex matches an entire string.
The forward slashes / /
mark the beginning and end of the regular expression.
^
and dollar sign $
match the beginning and end of the input.The caret lets us specify that the string has to start with a specific character, and the dollar that it has to end with the provided character. Anything in between also has to be matched.
If either of the conditions is not met, the test
method will return false
.
const str = 'hello'; const test = /^hell$/.test(str); console.log(test); // 👉️ false
If you need to get an array containing the match(es), you can use the String.match method.
const str = 'hello123'; const match = str.match(/^hello[0-9]+$/); console.log(match); // 👉️ ['hello123']
Our regular expression uses a character class []
to check for a range of
digits 0-9
at the end of the string.
The plus +
matches one or more of the preceding item (digits).
The match
method returns an array containing the matches or null
if the
regular expression is not matched in the string.
You often have to handle the possible return value of null
, by using the
logical OR (||) operator.
const str = 'hello123'; const match = str.match(/^bye[0-9]+$/) || []; console.log(match); // 👉️ []
If there is no match, we return an empty array. This would prevent us from
getting an error when we try to access the array element at index 0
on a
null
value.