Today we are quickly going to look out how the
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.
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