Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract last digit from string which contains chars and numbers

Tags:

javascript

How can i extract from string only last number which should be "5"?

var str = "1000040928423195 points added to your balance";
var str = parseInt(str);
var lastNum = str.substr(str.length - 1);
console.log(lastNum);
like image 806
Andrew Avatar asked Jul 08 '16 15:07

Andrew


People also ask

How do you extract the last digit of a string?

Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.

How do you extract the last digit of a number?

To find last digit of a number, we use modulo operator %. When modulo divided by 10 returns its last digit. To find first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.

How do you extract the last digit of a string in Python?

To get the last digit of a number in Python: Access the string representation of the number. Get the last character of the string representation. Convert the character to an integer.


1 Answers

Given your string...

var str = "1000040928423195 points added to your balance";

... we can extract all the numbers with a regex...

var onlyNumbers = str.replace(/\D/g,'');

... and, finally, get the last one:

var lastNumber = onlyNumbers.substring(onlyNumbers.length - 1);

Here is a demo:

var str = "1000040928423195 points added to your balance";
var onlyNumbers = str.replace(/\D/g,'');
var lastNumber = onlyNumbers.substring(onlyNumbers.length - 1);

console.log(lastNumber);
like image 72
Gerardo Furtado Avatar answered Oct 23 '22 13:10

Gerardo Furtado