/

The JavaScript String match() Method

The JavaScript String match() Method

Learn about the match() method in JavaScript for strings.

The match() method is used to search for a specified regular expression pattern inside a string. It returns an array of all the matches found or null if no matches are found.

Here are some examples of using the match() method:

Example 1:

1
2
'Hi Flavio'.match(/avio/)
// Output: Array [ 'avio' ]

Example 2:

1
2
'Test 123123329'.match(/\d+/)
// Output: Array [ "123123329" ]

Example 3:

1
2
'hey'.match(/(hey|ho)/)
// Output: Array [ "hey", "hey" ]

Example 4:

1
2
'123s'.match(/^(\d{3})(\w+)$/)
// Output: Array [ "123s", "123", "s" ]

Example 5:

1
2
'123456789'.match(/(\d)+/)
// Output: Array [ "123456789", "9" ]

Example 6:

1
2
'123s'.match(/^(\d{3})(?:\s)(\w+)$/)
// Output: null

Example 7:

1
2
'123 s'.match(/^(\d{3})(?:\s)(\w+)$/)
// Output: Array [ "123 s", "123", "s" ]

Example 8:

1
2
'I saw a bear'.match(/\bbear/)
// Output: Array ["bear"]

Example 9:

1
2
'I saw a beard'.match(/\bbear/)
// Output: Array ["bear"]

Example 10:

1
2
'I saw a beard'.match(/\bbear\b/)
// Output: null

Example 11:

1
2
'cool\_bear'.match(/\bbear\b/)
// Output: null

To learn more about regular expressions, check out my Regular Expressions tutorial.

tags: [“JavaScript”, “string methods”, “regular expressions”]