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 ?
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 ?
Share Improve this question asked Aug 5, 2013 at 12:28 Ashis KumarAshis Kumar 6,5542 gold badges23 silver badges36 bronze badges 5- This won't work? /.*([0-9]+)$/ – MightyPork Commented Aug 5, 2013 at 12:29
- do you always know the alpha part of that string? if so, you can replace that substring with '' and parseInt the rest – Kuro Commented Aug 5, 2013 at 12:30
- @Kuro: No the alpha part is dynamic. – Ashis Kumar Commented Aug 5, 2013 at 12:42
- @MightyPork: Can you show the full implementation. – Ashis Kumar Commented Aug 5, 2013 at 12:43
- I did now, check the answer – MightyPork Commented Aug 5, 2013 at 12:51
4 Answers
Reset to default 4This 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
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);
Try using this regular expression
var s = "gdgdfg45";
var matches = s.match(/\d+$/);
console.log(matches[0]);
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".