I am trying to do the following:
myVar = q.match(/[0-9]*\.[0-9]+|[0-9]+/);
However, when I type a decimal, myVar doesn't pick up the decimal until after I type decimal values.
Entered 3, myVar = 3
Entered ., myVar = 3
Entered 3, myVar 3.3
How do I modify this so myVar would equal 3. at the second step?
Thanks.
Don't use the + after [0-9] it means 1 or more occurrence. Try using *. It should work.
myVar = q.match(/[0-9]*\.[0-9]*|[0-9]*/);
Can be simplified to:
myVar = q.match(/[0-9]*\.[0-9]*/);
Problem is it is looking for atleast 1 number after the . In your case you want 0 or more.
It looks like you also want to match something like .3
, right? But you have to be sure your regex doesn't match a decimal point by itself .
. So you could do it with these alternations:
myVar = q.match(/\d+\.\d*|\.?\d+/);
\\d+\\.\\d*
matches 3.
, 3.3
, 3.33
etc.
\\.?\\d+
matches .3
, .33
, 3
, 33
, etc.
ALTERNATE: If you need to allow commas for thousands, millions, etc., use the following:
myVar = q.match(/\d{1,3}(,\d{3})*\.\d*|\d{1,3}(,\d{3})*|\.\d+/);
\\d{1,3}(,\\d{3})*\\.\\d*
matches 3.
, 3.3
, 3.33
, 3,333.3
etc.
\\d{1,3}(,\\d{3})*
matches 3
, 33
, 3,333
etc.
\\.\\d+
matches .3
, .33
, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.