This exercise is from jshero.com.
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.
Here is my working solution. I'm posting in hopes of receiving pointers on how I could have written the code more effectively.
function parseFirstInt(str) {
if (Number.isNaN(str) === true) {
return NaN;
} else {
let searchFrom = str.search(/[-+]?[0-9]+/g);
let searched = str.substr(searchFrom);
return parseInt(searched, 10);
};
}
Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN. parseFirstInt('No. -3) should return -3.
Thank you!
1 Answer 1
I believe you have either misunderstood the task, or misunderstood Number.isNaN
. In any case the if
doesn't do anything usefull. Number.isNaN
returns true
only when the value is exactly NaN
, which is not a valid input for your function anyway.
Then you are not checking if search()
isn't matching anything (and thus searchFrom
is -1
). It doesn't really matter, because substr(-1)
simply returns the last character, but it would make the code better to understand.
Use const
instead of let
when the value doesn't change.
Personnally I'd use .match()
instead of .search()
, because it returns the matched string directly (in an array):
function parseFirstInt(str) {
// Check if the paramter is a object with the method `match`
if (!str.match) {
return NaN;
}
const match = str.match(/[-+]?[0-9]+/);
if (match && match[0]) {
return parseInt(match[0], 10);
}
return NaN;
}
-
\$\begingroup\$ Thank you for your comment, I just have one question. Could you please explain what is happening here (!str.match) in the code you provided? \$\endgroup\$James Kemp– James Kemp2020年08月22日 15:24:54 +00:00Commented Aug 22, 2020 at 15:24