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:
'Hi Flavio'.match(/avio/)
// Output: Array [ 'avio' ]
Example 2:
'Test 123123329'.match(/\d+/)
// Output: Array [ "123123329" ]
Example 3:
'hey'.match(/(hey|ho)/)
// Output: Array [ "hey", "hey" ]
Example 4:
'123s'.match(/^(\d{3})(\w+)$/)
// Output: Array [ "123s", "123", "s" ]
Example 5:
'123456789'.match(/(\d)+/)
// Output: Array [ "123456789", "9" ]
Example 6:
'123s'.match(/^(\d{3})(?:\s)(\w+)$/)
// Output: null
Example 7:
'123 s'.match(/^(\d{3})(?:\s)(\w+)$/)
// Output: Array [ "123 s", "123", "s" ]
Example 8:
'I saw a bear'.match(/\bbear/)
// Output: Array ["bear"]
Example 9:
'I saw a beard'.match(/\bbear/)
// Output: Array ["bear"]
Example 10:
'I saw a beard'.match(/\bbear\b/)
// Output: null
Example 11:
'cool\_bear'.match(/\bbear\b/)
// Output: null
To learn more about regular expressions, check out my Regular Expressions tutorial.