-
Notifications
You must be signed in to change notification settings - Fork 2
JS String Prototype Match
The match()
method retrieves the matches when matching a string against a regular expression.
str.match(regexp)
regexp
A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj)
.
An Array
containing the matched results or null
if there were no matches.
If the regular expression does not include the g
flag, returns the same result as RegExp.exec()
. The returned Array
has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.
If the regular expression includes the g
flag, the method returns an Array
containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null
.
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
var str = 'For more information, see Chapter 3.4.5.1';
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);
console.log(found);
// logs ['Chapter 3.4.5.1', 'Chapter 3.4.5.1', '.1']
// 'Chapter 3.4.5.1' is the first match and the first value
// remembered from `(Chapter \d+(\.\d)*)`.
// '.1' is the last value remembered from `(\.\d)`.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links