Regex that Match the last digit if it's alone

54 views Asked by At

I have a string like so:

11547778:115,12

My question is, is there an expression that match the last number if it is made of a single digit then use the $.replace() function to put a 0 in front of it for exemple:

84500015:217,8 will become-> 84500015:217,08
3

There are 3 answers

4
Rory McCrossan On BEST ANSWER

To achieve this you can look for a string which specifically ends with a comma and a single number, something like this:

['11547778:115,12', '19038940:123,a', '84500015:217,8'].forEach(function(val) {
  var foo = val.replace(/,(\d)$/, ',0$1');
  console.log(foo);
});

1
Djory Krache On

You can try something like

"11547778:115,2".replace(/,([0-9])$/g,',0$1') -> "11547778:115,02"
"11547778:115,12".replace(/,([0-9])$/g,',0$1') -> "11547778:115,12"
0
Alex K. On

Non-RE approach

if (str.substr(-2, 1) == ",") 
    str = str.replace(",", ",0");