I'm new to JS - this might be easy for you guys to answer. I've been reading on regular expression but couldn't figure out the full meaning of this code:
I've been asked to write a myParseInt method with the following rules:
- It should make the conversion if the given string only contains a single integer value (and eventually spaces - including tabs, line feeds... - at both ends).
- For all other strings (including the ones representing float values), it should return NaN.
- It should assume that all numbers are not signed and written in base 10.
The answer is:
function myParseInt ( str ) { return /^\s*\d+\s*$/ . test (str) ? + str : NaN; }
(please correct me if I'm wrong!) But I sort of understand the first and last part (/^\s*
and \s*$
) where it matches the beginning and end of str input with white space character. The \d+
part matches digit characters 1 or more times.
The .test(str)
part matches the str with the stated regular expressions and gives it a true or false value -
but why is there ? after .test(str)
, then + str: NaN;
? I am unsure what does the ?
do, the :
syntax. I know it has something to do with if it doesn't match, gives NaN
. But I am trying to get clarifications regarding the syntax which I couldn't find on MDN.
Many thanks!