1
\$\begingroup\$

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!

\$\endgroup\$
0
2
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • \$\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 Aug 22 '20 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.