How to Check if String Matches Pattern in JavaScript
In JavaScript, you can check if a string matches a pattern using the
RegExp.test() method or the string method match(). Both use regular expressions to define the pattern you want to check against.Syntax
Use the RegExp.test() method to check if a string matches a pattern. It returns true if the pattern is found, otherwise false.
Syntax:
pattern.test(string)- Returnstrueorfalse.string.match(pattern)- Returns an array of matches ornullif no match.
javascript
const pattern = /yourPattern/; const string = "your string here"; const result = pattern.test(string); // true or false const matches = string.match(pattern); // array or null
Example
This example checks if the string contains only digits using a regular expression. It shows how to use test() and match() methods.
javascript
const pattern = /^\d+$/; // pattern for digits only const string1 = "12345"; const string2 = "123abc"; console.log(pattern.test(string1)); // true console.log(pattern.test(string2)); // false console.log(string1.match(pattern)); // [ '12345', index: 0, input: '12345', groups: undefined ] console.log(string2.match(pattern)); // null
Output
true
false
[ '12345', index: 0, input: '12345', groups: undefined ]
null
Common Pitfalls
Common mistakes include:
- Not using the correct regular expression delimiters
/pattern/. - Forgetting to escape special characters in the pattern.
- Using
match()expecting a boolean instead of an array ornull. - Confusing
test()andmatch()return types.
Example of wrong and right usage:
javascript
// Wrong: expecting boolean from match() const pattern = /abc/; const string = "abcdef"; const resultWrong = string.match(pattern) === true; // false, match returns array or null // Right: use test() for boolean const resultRight = pattern.test(string); // true console.log(resultWrong); // false console.log(resultRight); // true
Output
false
true
Quick Reference
| Method | Description | Return Type |
|---|---|---|
| RegExp.test(string) | Checks if pattern matches string | Boolean (true/false) |
| string.match(pattern) | Finds matches of pattern in string | Array of matches or null |
| RegExp.exec(string) | Executes a search for a match | Array with match details or null |
Key Takeaways
Use RegExp.test() to get a simple true or false if a string matches a pattern.
Use string.match() to get detailed match results or null if no match.
Always write regular expressions between slashes, like /pattern/.
Escape special characters in patterns to avoid errors.
Remember test() returns boolean, match() returns array or null.