Last updated: Mar 4, 2024
Reading timeยท2 min
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.
const str = 'hello'; const test = /^hello$/.test(str); console.log(test); // ๐๏ธ true const match = str.match(/^hello$/); console.log(match); // ๐๏ธ ['hello']
The
RegExp.test()
method returns true
if the regular expression is matched in the string and
false
otherwise.
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 given
character and the dollar sign $
that it has to end with the specified
character.
Anything in between also has to match.
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
The regular expression doesn't match the entire string, so the test()
method
returns 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]+$/g); console.log(match); // ๐๏ธ ['hello123'] console.log(match[0]); // ๐๏ธ 'hello123'
The String.match() method matches a string against a regular expression.
[]
to check for a range of digits 0-9
at the end of the string.The plus +
matches one or more of the preceding items (digits).
The match()
method returns an array containing the matches (if any) or null
if no matches are found.
Use the logical OR (||) operator to provide an empty array as a fallback in case
null
is returned.
const str = 'hello123'; const match = str.match(/^bye[0-9]+$/) || []; console.log(match); // ๐๏ธ []
If there is no match, we return an empty array. This prevents us from getting an
error when we try to access the array element at index 0
on a null
value.
You can learn more about the related topics by checking out the following tutorials: