Help: Find Numbers with Regular Expressions

Help: Find Numbers with Regular Expressions
0

#1

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:


#2

+ 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”.


#3

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


#4

Try it and find out. :smiley:


#5

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


#6

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


#7

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.


#8

Yup! The token + will grab multiple sequential digits.


#9

Thanks for you help. :grinning: