Home > Mobile >  Convert string of character and number into integer?
Convert string of character and number into integer?

Time:03-18

I want to convert this string "F1" into an integer 1.

For example

"F1" ===> 1
"F2" ===> 2
"F3" ===> 3

So far, this is what I've done

parseLevel: function(level) {
    var levels = {
        "F1": 1,
        "F2": 2
    };
    return levels[level];
}

Here's the function

parseLevel: function (level) {
  return parseInt(level, 10);
}

I'm getting an error says it's NaN

CodePudding user response:

Since the string you pass has a leading F in it; parseInt can't figure out what integer F1 could be so just strip the F of the string.

parseLevel: function (level) {
  return parseInt(level.slice(1), 10);
}

CodePudding user response:

Here is an example of how you could parse any string and only use its digits. to parse an integer.

let s = "ajs382bop";//can be any string it will strip all non digits
function stripAndReturnNumber(s){
    return parseInt(s.replace(/\D/g, ""));
    //This will replace all non digits with nothing and leave all digits remaining.
    //Then it will return the resulting integer.
}
console.log(stripAndReturnNumber(s));//382

CodePudding user response:

parseLevel: function (level) {
  return parseInt(level.replace("F", ""));
}
    
  • Related