This question already has answers here:
How do you use the ? : (conditional) operator in JavaScript?
(20 answers)
Closed 6 years ago.
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!
The ? is a ternary operation.
You write a condition that returns true/false followed by a question mark, then what to return for truthy and falsy.
It is taken from C.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Related
This question already has answers here:
How do I match an entire string with a regex?
(8 answers)
What is the meaning of + in a regex?
(5 answers)
Closed 6 months ago.
So I've read a lot of posts and documentation on the + operator for JS regex, but I'm still unsure of what it wouldo do.
For example, one of the websites I looked after gave the following example:
const nums = /\d+/
console.log(nums.test('456'))
Says it would look for infinite possibilites for d. But then...
const nums = /\d/
console.log(nums.test('456'))
... has the same result.
So I tried using numbers... for instance:
const nums2 = /45/
const nums 3 = /45+/
console.log(....
But testing both regex would STILL give the same result. If I put any numbers before or after 45 with or without the + it will still give me a "true" if 45 is togheter.
So can someone explain what the + symbol in regex means and it's usage in a way I can understand?
There's no difference in the cases you tried -- if there's one digit, then there's also one or more digit, so they both match.
But if you use it together with other patterns you can have a difference.
console.log(/A\dB/.test("A123B"));
console.log(/A\d+B/.test("A123B"));
The first one is false because it only matches a single digit between A and B; the second is true because it matches any number of digits.
The difference can also be useful if you use .match() instead of .test(). This returns the part of the string that matched the regexp, and \d+ will return the entire number, while \d will just return the first digit.
This question already has answers here:
How does parseInt() in Javascript work?
(4 answers)
Closed 3 years ago.
parseInt('5aab4') //5
// I expect the output is NaN.
My logic fails, due to parseInt. I assume that parseInt always returns NaN, when the input contains a letter?
No, parseInt() allows "garbage" (non-number) characters after some numeric characters. The parseFloat() function has the same "feature".
If you want to get a number, you can use Number("123") or simply the + unary operator. However those accept any JavaScript number, including ones with fractional parts or numbers in scientific notation. But those methods will fail and give NaN if the string input is not a valid numeric constant.
You could do something like
if (+someString === Math.floor(+someString))
I guess.
edit — a comment notes that you'd also want to check the degenerate case of an empty or all-space string too. A simple regular expression (/^\d+$/) followed by a sanity check that it's not 200 digits long (amonth possibly other things) is another alternative.
If you were wanting to check NaNanother way would be to test it with isNaN().
isNaN() will return a boolean giving you a verification for a given input.
parseInt('5aab4') //5
isNaN('5aab4') // true
This question already has answers here:
Why does the order of alternatives matter in regex?
(1 answer)
Why order matters in this RegEx with alternation?
(3 answers)
Closed 3 years ago.
I am trying to replace 2% with ''(empty) using regexp concept. If input string is either % or 2%, it should be replaced with ''(empty):
const str = "2%";
console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));
(a|b) Matches the a or the b part of the subexpression.
"2%".replace(/^\d%$|\d(?=%)/, ''). This works well.
But, "2%".replace(/\d(?=%)|^\d%$/, '') does not.
The difference is in what the regex tries to match first. The left expression takes precedence. The right is only tried when the left one fails to match.
This question already has answers here:
Why is one string greater than the other when comparing strings in JavaScript?
(5 answers)
Closed 6 years ago.
I took a JS course on a website , and in one of the lessons there was a piece Of code that did not make sense to me :
the code is in the picture , why str1 is less then str2 ?
Strings are compared based on standard lexicographical ordering, using Unicode values. That means "a" < "b" and "c" > "b"
Two strings are strictly equal when they have the same sequence of
characters, same length, and same characters in corresponding
positions. source
var str1 = "aardvark";
var str2="beluga";
console.log(str1 < str2);//true
console.log(str1.length < str2.length);//false
This compares each character from 0-index, for example "a"<"b" thi is true. If there are equal, it compares next index, and next, ...
"aad">"aac", because, twice "a"="a" and then "d">"c"
JavaScript in this case will compare the strings lexographically character by character, where the letter 'a' is lower than the letter 'b' and so on. It works for numbers too, and the uppercase alphabet is considerd higher than the lowercase alphabet.
So, in your example, 'a' < 'b' and therefore the statement is true.
This question already has answers here:
How to convert a currency string to a double with Javascript?
(23 answers)
Closed 7 years ago.
What I'm talking about is reading a string into a Number, e.g.
"$107,140,946" ---> 107140946
"$9.99" ---> 9.99
Is there a better way than
dolstr.replace('$','');
dolstr.replace(',','');
var num = parseInt(dolstr,10);
???
Using regex is much simpler to read and maintain
parseFloat(dolstr.replace(/\$|,/g, ""));
You can just put all of this in oneliner:
parseFloat(dolstr.replace('$','').split(",").join(""))
Notice that I do not replace the second one, because this will remove just the first ','.
Using a simple regex and the string's replace function
parseFloat(dolstr.replace(/[^\d\.]/g, ''))
Breakdown
It replaces every instance of a character that is not a digit (0 - 9) and not a period. Note that the period must be escaped with a backwards slash.
You then need to wrap the function in parseFloat to convert from a string to a float.
Assuming input is always correct, just keep only digits (\d) and the dot (\.) and get rid of other characters. Then run parseFloat on the result.
parseFloat(dolstr.replace(/[^\d\.]/g, ''))