DEV Community

SCDan0624
SCDan0624

Posted on

Javascript Regex Part 1 Test/Match Methods

Intro
Regular expressions are used in Javascript to help you match strings patterns. They can useful to search for key words or patterns in large amounts of text.

Test Method
Javascript has multiple ways to use regular expressions. The first method we will look at is the test method. The test method takes the regex and applies it to a string. This will return true or false depending on if your pattern matches or not:

const testStr = "My favorite color is blue"
const testRegex = /blue/
testRegex.test(testStr) // Returns true
Enter fullscreen mode Exit fullscreen mode

Using the same example as above you can search for multiple patterns using the or operator:

const testStr = "My favorite color is blue"
const testRegex = /blue|color/     // searches for blue or color
testRegex.test(testStr) // Returns true
Enter fullscreen mode Exit fullscreen mode

Ignore case while matching
In our previous example we would only get a match if the letter case was the same. What if you want a match while ignoring the letter case? You can do this by adding an ignore flag at the end of your search:

const testStr = "AmazonPrime"
const testRegex = /amazon/i   // the i at the end is the ignore flag
testRegex.test(testStr) // Returns true
Enter fullscreen mode Exit fullscreen mode

Match Method
So far we have only been checking if a pattern exists within a string and returning a boolean value of true or false. You can also find the actual matches within a string with the match method:

let myStr = "Basketball team";
let myRegex = /team/;
myStr.match(myRegex); // Returns ["team"]
Enter fullscreen mode Exit fullscreen mode

Global flag
What if you want to search for a pattern more than once? This is where you use the global flag:

let myStr = "Basketball team team";
let myRegex = /team/g;
myStr.match(myRegex); // Returns ["team","team"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)