Reputation: 43
I have some strings like:
row_row1_1, row_row1_2, row_row1_13, row_row1_287, ...
and I want to take the last numbers of that strings, ut can be 1, 2, 13 or 287. That strings are generated automatically and I can't control if there is going to be 1 number, 2 numbers, 3 numbers...
I would like to make a function that takes the last number character, or the numbers after the second '_' character. is there any idea?
Thank you very much!
Upvotes: 0
Views: 489
Reputation: 170
If your strings always follow this pattern str_str_str then you can use the split
method and get the 2º index of the array, like this:
var number = str.split('_')[2];
Upvotes: 2
Reputation: 2837
Taking the last numeric characters
function getNumericSuffix(myString) {
var reversedString = myString.split('').reverse().join('');
var i, result="";
for(i = 0; i < reversedString.length; i++) {
if(!isNaN(reversedString[i])) {
result = reversedString[i] + result;
} else break;
}
return parseInt(result); // assuming all number are integers
}
Upvotes: 0
Reputation: 21465
As @PaulS said, you can always use regex for that purpose:
var getLastNumbers = function(str)
{
return str.replace(/.+(_)/, '');
};
getLastNumbers("row_row1_287"); // Will result -> 287
Upvotes: 1