Skip to content

String match in JavaScript

Today we are quickly going to look out how the String match() works. This method makes our string contains check easy.



It allows us to do the creative way of checking using the Regular Expression. We can extract the keyword from a long string and replace with the string matches the regex and we can efficiently store the matched data into a new array.

Parameter: A regular expression object.

Return type: If the match found for the given regex then it return new array, else return null value.

Below is the simple example

var str = "Hello Poopcoder!"; 
var regExp = /o/;
console.log(str.match(regExp));    // ["o"];

The above regex will return only the first match. This makes easy when we know the exact string going to match. When we learn about Regular Expression clearly then the usecase of match method will be more efficient.

Additional Flags

g: If the regular expression contains this params then the method search the matched string globally in the string. Same result as regexp.exec(string).

var str = "Fred fed Ted bread, and Ted fed Fred bread"; 
var res = str.match(/ed/g);
console.log(res); //["ed","ed","ed","ed","ed","ed"];

i: This allows to get match with case insensitivity.

var str = "FrEd fed Ted bread, and Ted fEd Fred bread"; 
var res = str.match(/ed/gi);
console.log(res);  //["Ed","ed","ed","ed","Ed","ed"];

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.