1

I am using javascript, i want to get the last digit of a string. The following is my code,

var idval = focused.id;
var lastChar1 = idval.substr(idval.length - 1);

Suppose myid name is idval5 means, it correctly returns 5

But if id name is idval21 means, it is returning 1 only. But i want 21 as a output.

Please anyone help

KMS
  • 566
  • 4
  • 16

1 Answers1

5

You could use a regular expression which searches for digits and for the end of the string.

function getLastDigits(s) {
    return s.match(/\d+$/)[0];
}

console.log(['idval2', 'idval21'].map(getLastDigits));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392