Here’s a string value, containing one number (
1995) that is assigned to a variable called
Now let’s attach the
match() method to the variable, and add
\d+ as an argument, so it looks like this
\d+ is a regular expression (RegEx) meta character that means “match 1 or more digits”.
And let’s print the result:
console.log(stringWithOneNumber.match(/\d+/)) // ["1995"]
What if a string has two or more numbers?
No problem, you just add a global
g flag to the
match() argument. Let’s use the example from earlier, but this time the string sentence contains two numbers:
Now add the
match() method with
Print the result:
console.log(stringWithMultipleNumbers.match(/\d+/g)) // ["1995", "2020"]