1

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

6
  • Does your string always start with an "F"? And will it always have a number after the first "F"? Commented Mar 18, 2022 at 4:56
  • @NalinRanjan yes Commented Mar 18, 2022 at 4:57
  • what result should it produce if the input is invalid? NaN or 0? Commented Mar 18, 2022 at 4:59
  • @NalinRanjan it says NaN Commented Mar 18, 2022 at 5:01
  • There is an answer below, does it work for you ? Commented Mar 18, 2022 at 5:02

2 Answers 2

4

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.