test() JavaScript RegExp Method – How to Test a String
Whenever you use test() on a regular expression, the method does the following:
- It tests its string argument for the regular expression’s pattern.
- It returns
true
if it finds the RegExp pattern in the string. Otherwise, it returnsfalse
.
Use RegExp’s test() method to test if a string contains a regular expression pattern.
Syntax of the test()
Method
test()
accepts a string argument. Here is the syntax:
RegExp.test("stringToTest");
Examples
Below are examples of the test()
method.
Test a string for a case-insensitive Color
pattern
/Color/i.test("My best color is blue.");
// The invocation above will return: true
The snippet above returned true
because the computer found the RegExp pattern in the string argument.
In other words, the test for a case-insensitive Color
pattern in the string argument matched the string’s color
text. Therefore, test()
returned true
.
Test if Sweetly
is at the end of "CodeSweetly"
/Sweetly$/.test("CodeSweetly");
// The invocation above will return: true
Test if a string contains @
/@/.test("Learn JavaScript at codesweetly.com");
// The invocation above will return: false