match method in JavaScript regular expressions

The match method finds the first match with a regular expression. It returns an array, the zero element of which will contain the found substring.

Let's look at an example. Let's say we have the following string:

let str = 'xax xaax xaaax';

Let's apply our method with a regular expression to this string:

let res = str.match(/xa+x/);

The zero element of the resulting array will contain the first match with the regex:

console.log(res[0]); // shows 'xax'

In this case, the result will have additional properties. The index property will contain the position at which the match was found:

console.log(res.index); // shows 4

And in the input property - the string on which the search was applied (information of doubtful value):

console.log(res.input); // shows 'xax xaax xaaax'

Given a string:

let str = 'aaa 123 bbb';

Find a substring containing digits.

Given a string:

let str = 'aaa 123 bbb';

Find a position of the first digit.

enru