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.
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;
};
<br>
<br>
<br>
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--------------------
Please explain if possible as to how the loop works. This code is correct and it works.