Richard
Richard

Reputation: 1048

Regex that Match the last digit if it's alone

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

Upvotes: 1

Views: 54

Answers (3)

Alex K.
Alex K.

Reputation: 175976

Non-RE approach

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

Upvotes: 1

Djory Krache
Djory Krache

Reputation: 347

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"

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337714

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);
});

Upvotes: 5

Related Questions