Help: Find Numbers with Regular Expressions

What changes if I put ‘/\d/g;’ instead of ‘/\d+/g;’?

Your code so far

// Setup
var testString = "There are 3 cats but 4 dogs.";

// Only change code below this line.

var expression = /\d+/g;  //Change this line

// Only change code above this line

// This code counts the matches of expression in testString
var digitCount = testString.match(expression).length;

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0.

Link to the challenge:

+ means "one or more of this thing.

If we are looking at a string containing “123”, then /\d/g will have three different matches: “1”, “2”, and “3”. /\d+/g will have one match: “123”.

1 Like

If I put the ‘+’ in the /\d/g will the program give me 1 (“34”) instead of 2 (“3”, “4”)?

Try it and find out. :smiley:

They both give me 2. Shouldn’t /\d/g give me 1 (“34”)?

/\d/g will give you one match per digit in your string.

Actually, I think I understand now. The program gives me 2 because the 3 and the 4 are in different spots. If is was “There are 32 cats but 4 dogs.” the program would still give me 2 because it combines 32 into one number.

Yup! The token + will grab multiple sequential digits.

Thanks for you help. :grinning: