JavaScript String.match() Method
-
Syntax of JavaScript
string.match()
: -
Example Codes: Use the
string.match()
Method to Find a Match Value With Regular Expression -
Example Codes: Use the
string.match()
Method to Find a Match Value With Regular Expression Flag-g
-
Example Codes: Use the
string.match()
Method to Find a Match Value With Regular Expression Flag-g
and-i
In JavaScript, the string.match()
method is used to find the matched values from a string. This method expects a regular expression as a parameter and returns the result in an array.
This method returns the first match if no parameter is passed.
Syntax of JavaScript string.match()
:
string.match(regExp)
Parameter
regExp |
A regular expression is used to find the matched value from a string. Different flags -g and -i can be used as regular expressions. |
Return
An array of matched results against the regular expression will be returned. If no such value matches, it will produce a null
.
Example Codes: Use the string.match()
Method to Find a Match Value With Regular Expression
let string = 'Your guess is As good as mine'
console.log(string.match(/as/))
Output:
[
'as',
index: 22,
input: 'Your guess is As good as mine',
groups: undefined
]
We provided as
to the string.match()
method and used regular expression. In the string, two values are matched with as
, but one is in uppercase, and the other is in lowercase.
It matched with the lowercase and returned the result.
Example Codes: Use the string.match()
Method to Find a Match Value With Regular Expression Flag -g
let string = 'Your guess is As good as mine'
console.log(string.match(/as/g))
Output:
[ 'as' ]
In the regular expression, the flag -g
refers to the global. When we used it in the string.match()
method, it should return all the values that matched with as
.
In this case, we should get two as
, but we only got one because of case sensitivity. To get all the values, we need to use another flag, -i
along with -g
.
Example Codes: Use the string.match()
Method to Find a Match Value With Regular Expression Flag -g
and -i
let string = 'Your guess is As good as mine'
console.log(string.match(/as/gi))
Output:
[ 'As', 'as' ]
In the regular expression, the flag -i
refers to case insensitivity. We used this flag along with the global flag; as a result, the global flag returned an array with all matched values of as
.
Niaz is a professional full-stack developer as well as a thinker, problem-solver, and writer. He loves to share his experience with his writings.
LinkedIn