Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Question:

Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.

Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.


Explanation:

> we declare a function 'parseFirstInt'

> it has 1 parameter 'input'

> we declare a variable 'inputToParse'

> we initialize it with a value of the input string

> we use a 'for loop' to loop over the elements of the input string

> we then declare another variable inside the 'for loop' which is 'firstInt'

> we initialize its value with the output we get when we run the parseInt method on variable 'inputToParse' and store them in the firstInt variable

> we then open an if else statement

> our condition is plain & simple

> if value of 'firstInt' is NaN then we want it to exit the loop and return NaN

> if value of 'firstInt' is not NaN then we want it to execute the block of code in the if / else loop

> we keep checking for the first integer by using the loop

---------stopped understanding from here---------

What I have tried:

Answer:

function parseFirstInt(input) {
let inputToParse = input;
for (let i = 0; i < input.length; i++) {
let firstInt = parseInt(inputToParse);
if (!Number.isNaN(firstInt)) {
return firstInt;
}
inputToParse = inputToParse.substr(1);
}
return NaN;
};
Posted
Comments
Patrice T 10-Jun-21 15:54pm    
Give detail on what you don't understand.
SeeSharp2 10-Jun-21 16:03pm    
What is the question?
jaket-cp 11-Jun-21 5:42am    
created a fiddle and your answer is getting the expected results
https://jsfiddle.net/dmy7x234/
As Patrice T said - what do you not understand
jaket-cp 11-Jun-21 8:49am    
have a read of this answer it might help
https://forum.freecodecamp.org/t/cannot-understand-this-javascript-nan-practice-problem-please-help-in-explaining-it/464362/30
SeeSharp2 11-Jun-21 9:18am    
You keep replying to my comment instead of adding your own.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900