Andrew
Andrew

Reputation: 1575

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

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

Upvotes: 6

Views: 6527

Answers (7)

Gerardo Furtado
Gerardo Furtado

Reputation: 102218

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

Upvotes: 10

Mikiku
Mikiku

Reputation: 152

var digit = /.*(\d)/.exec("awoo123awoo")[1];

3

Upvotes: 1

Michael Jones
Michael Jones

Reputation: 2282

Try parsing it with a Regular Expression like so :)

string = "120394023954932503 fdsaf fdsaf dasfasd";
regex = /([0-9]*)/g;
match = regex.exec(string);
last_num = match[0].substr(match[0].length - 1);
console.log(last_num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="string_val"></div>

Upvotes: 2

BenG
BenG

Reputation: 15164

Use the regex \d+(\d) to match multiple digits followed by a digit.

\d will occupy as many as possible, where (\d) will match the last.

Then get the last number from the first group [1].

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

var match = /\d+(\d)/g.exec(str)[1];

console.log(match);

Upvotes: 1

DAXaholic
DAXaholic

Reputation: 35408

Use a regex like /\d+(\d)/

var str = "1000040928423195 points added to your balance";
str.match(/\d+(\d)/)[1]

Upvotes: 4

elreeda
elreeda

Reputation: 4597

Just add toString() after parseInt

var str = "1000040928423195 points added to your balance";
var str = parseInt(str).toString();
var lastNum = str.substr(str.length - 1);
console.log(lastNum);

Upvotes: 4

Scott Hunter
Scott Hunter

Reputation: 49920

After your second line, str isn't a string any more; it is an integer. As such, you can extract the last digit with str % 10; if necessary, convert that to a string.

Upvotes: 2

Related Questions