2
\$\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!

asked Aug 22, 2020 at 1:14
\$\endgroup\$
0

1 Answer 1

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;
}
answered Aug 22, 2020 at 8:21
\$\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\$ Commented Aug 22, 2020 at 15:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.