Skip to content

The String match() method

New Course Coming Soon:

Get Really Good at Git

Find out all about the JavaScript match() method of a string

Given a regular expression identified by regex, try to match it in the string.

Examples:

'Hi Flavio'.match(/avio/)
// Array [ 'avio' ]

'Test 123123329'.match(/\d+/)
// Array [ "123123329" ]

'hey'.match(/(hey|ho)/)
//Array [ "hey", "hey" ]

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

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

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

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

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

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

'I saw a beard'.match(/\bbear\b/) //null

'cool_bear'.match(/\bbear\b/)     //null

To know more about Regular Expressions, see my Regular Expressions tutorial.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: