I'm trying to match a number at the end of a string, using a regex. For example, the string might look like:
var foo = '101*99+123.12'; // would match 123.12
var bar = '101*99+-123'; // would match -123
var str = '101*99+-123.'; // would match -123.
This is what I've got so far, but it seem to match the entire string if there is no decimal point:
foo.match(/\-?\d+.?\d+?$/);
I take this to mean:
\-?
: optional "-" symbol\d+
: 1 or more digits.?
: optional decimal point\d+?
: optional 1 or more digits after decimal point$
: match at the end of the stringWhat am I missing?
.
matches any character. You need to escape it as \.
Try this:
/-?\d+\.?\d*$/
That is:
-? // optional minus sign
\d+ // one or more digits
\.? // optional .
\d* // zero or more digits
As you can see at MDN's regex page, +?
is a non-greedy match of 1 or more, not an optional match of 1 or more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With