aveli93
aveli93

Reputation: 43

How to extract last characters of type number javascript/jquery

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

Answers (3)

Cledson Araújo
Cledson Araújo

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

Merhawi Fissehaye
Merhawi Fissehaye

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

DontVoteMeDown
DontVoteMeDown

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

Fiddle

Upvotes: 1

Related Questions