June 2022

Capture A Regular Expression Match In JavaScript

Basic way to find a string inside another string with a regular expression. If the pattern hits, like in this example, the result is shown. Otherwise the 'no match found' message is shown.

const source = "the quick brown fox"

const pattern = /quick (.*?) fox/

const match = source.match(pattern)

if (match !== null) {
    console.log(match[1])
} else {
    console.log('no match found')
}
Output:
brown
end of line