Mike Van Stan
Mike Van Stan

Reputation: 396

Capture first digit after decimal

I have this line here:

\d(?!.*\d)

whereby it captures the last digit after a period. i.e: 6.3059

Will return "9", HOWEVER, what I really want it to do - is return 3.

Upvotes: 5

Views: 1026

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Your regex matches any digit that is not followed by a digit, that is why you get 9 as output.

You can use a capturing group:

\d\.(\d)

The value will be in Group 1. See demo.

JS code:

var re = /\d\.(\d)/; 
var str = '6.3059';
var m;
 
if ((m = re.exec(str)) !== null) {
    document.getElementById("r").innerHTML = m[1];
}
<div id="r"/>

Upvotes: 3

Related Questions