Ashis Kumar
Ashis Kumar

Reputation: 6544

Getting numeric value from a alpha numeric string in javascript

I have a string "RowNumber5", now i want to get the numeric value "5" from that string using Javascript.

Note: Numeric value will be always at the end, after alphabets, that means numeric value will never occur in between alphabets. Example -

 Result45 - Yes
 Result45Abc - Never

I can get this "5" by some thing like this

var t = "Ruby12";
var y = parseInt(t.split('').reverse().join(""));
if(!isNaN(y)) {
    y = y.toString().split('').reverse().join("");
}
else {
    y = "";
}
console.log(y);

Any shot way? or Better approach for this ?

Upvotes: 3

Views: 3509

Answers (4)

tb11
tb11

Reputation: 3106

This is what regexes were made for!

var matches = /\d+$/.exec("Ruby12");
matches[0];  //returns 12

var matches = /\d+$/.exec("sfwfewcsd098");
matches[0];  //returns 098

var matches = /\d+$/.exec("abc"); //matches returns null

Upvotes: 4

Vinod Louis
Vinod Louis

Reputation: 4876

Try using this regular expression

var s = "gdgdfg45";
var matches = s.match(/\d+$/);
console.log(matches[0]);

Upvotes: 1

MightyPork
MightyPork

Reputation: 18861

Here's a regex solution:

// input string
var t = "Ruby12";

var num = null;    
var match = t.match(/([0-9]+)$/);    
if(match!=null) num = parseInt(match[1]);

// num now contains null or number

// debug
console.log(num);

Upvotes: 1

faino
faino

Reputation: 3224

I would go with the divide and conquer method, working through all strings that may contain numbers:

var t = "Ruby12";
function get_numbers(str) {
    var parts = str.split(""), nums = "";
    for(var i = 0, len = parts.length; i < len; i++) {
        nums += (isNaN(parts[i])) ? "" : parts[i].toString();
    }
    return(nums);
}

var numbers = get_numbers(t);
alert(numbers);

Which would give you "12".

Upvotes: 0

Related Questions