DEV Community

SHivam Sinha
SHivam Sinha

Posted on

Help me with the code, most of the test cases passed but when a negative number encounter it return its positive value.

var input =function(t){
var n = String(t)
var reg = /\d+/
var result = n.match(reg)
var a = parseInt(result)

if (result){
return a
}
else{return 'Nan'}
}
console.log(input('-18.12'))

Top comments (6)

Collapse
 
jrogers8835 profile image
jrogers8835

Also I assume you're doing this as a learning excercise, as there are easier ways of doing this if you're just looking for a utility function?

Collapse
 
strangelestrade profile image
SHivam Sinha

Yes as a beginner I am learning the stuff.

Collapse
 
jrogers8835 profile image
jrogers8835

See my other comment for guidance. If you can't figure it out after a few hours of playing with regex, message me and I'll send you the pattern.

Collapse
 
jrogers8835 profile image
jrogers8835

When you convert to a string the '-' loses context. You would need ^[-+]?\d*$ to allow the negative sign. This doesn't work for decimals btw. Not sure if you want those.

Collapse
 
strangelestrade profile image
SHivam Sinha

still not working
gives an unexpected error.
Help

Collapse
 
jrogers8835 profile image
jrogers8835

I did mention it doesn't work for decimals. Regex is useful. Use this site for testing and see what you can find from google to account for decimals.
regexr.com/
Hint: '.' Is a special character