JavaScript test if number variable is a number [duplicate] - javascript

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 5 years ago.
I’m loading a JSON file a reading the values into an array using a for loop
I’m concerned that sometimes the JSON file might become corrupted ie the values Im reading in might become ASCII letters ie 1t3 where the value should of been 123
Is there a test case where you could say if values[a] does not equal a number then set it to “ “ or blank
Thanks,
Ben

You could use the parseInt() function and check if it returns an integer or NaN. You can check out information on it on W3schools or the MDN Web Docs.
However, in my opinion, it would be better to use regular expressions. If you read the w3schools examples for parseInt(), they show that "0x10" is read as 16.
For a regular expression, try the following:
function isNumber(n) {
// Added checking for period (in the case of floats)
var validFloat = function () {
if (n.match(/[\.][0-9]/) === null || n.match(/[^0-9]/).length !== 1) {
return false;
} return true;
};
return n.match(/[^0-9]/) === null ? true : validFloat();
}
// Example Tests for Code Snippet
console.log(isNumber("993"));
console.log(isNumber("0t1"));
console.log(isNumber("02-0"));
console.log(isNumber("0291"));
console.log(isNumber("0x16"));
console.log(isNumber("8.97"));
The MDN Web Docs have a super helpful page on Regular Expressions.

Related

Convert "10/2" to a number? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 1 year ago.
I am working on a discord.js and have a found the following problem, I want to convert the users input into a number I am working on a calc bot so the arguments were like 10/2 but I couldn't find a method of converting the string into a number so I thought i would ask, I thought maybe the Number function could work but it didn't and tried using arrays but the join function simply converts it to a string. Anyone know how to solve this?
If you want to avoid the use of eval, you need to parse out the numbers, convert them to numbers, and perform the appropriate operation.
const rx = /(\d+(?:\.\d+)?)\s*([+\-\*\/%])\s*(\d+(?:\.\d+)?)/;
function math(str) {
const [full, lhs, op, rhs] = rx.exec(str);
let retval
switch (op) {
case '+':
retval = Number(lhs) + Number(rhs);
break;
// etc...
}
return retval;
}
console.log("1 + 1 = ", math("1 + 1"));
console.log("1.1 + 1.1 = ", math("1.1+1.1"));
Note that the code above doesn't have any error checking to bail if the string provided isn't a valid operation, or if the numbers aren't really numbers. It's only an example of how you can use a regular expression to get these values, and avoid using the potentially dangerous eval.
The easiest way to do this is by using eval() which takes a string containing javascript code, evaluates it, and returns the result.
WARNING: this is very dangerous and you can send any javascript code with it and javascript will happily execute it.
This would give users of the bot the ability to do any command and basically take remote control of your computer/server.
To protect yourself from this you should make sure that the string only contains some allowed characters like this:
const allowedChars = "1234567890/*+-% ";
const input = "2323 + 323";
if (![...input].some(x => !allowedChars.includes(x))) {
// safe to evaluate
const result = eval(input);
} else {
// not safe to execute
}

What exactly is (alert(1),"") in javascript [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 2 years ago.
I tried doing google gruyeres XSS challenges (http://google-gruyere.appspot.com/part2), and at the stored AJAX XSS challenge they have the following code part for the JSON response:
all <span style=display:none>"
+ (alert(1),"")
+ "</span>your base
The interesting part is: (alert(1),"")
According to the solution provided, the empty string gets returned. According to my testing, the alert(1) still gets exectued.
Is this some sort of function shorthand, or what would this be called in JS?
Why does it execute the alert, but then return the empty string?
Thank you very much for any help!
Best regards,
Rolf
This is the comma operator. The code executes alert(1), discards its return value, then evaluates "". Since this is the last item in the expression, its value is returned, which is empty string.
The tutorial I linked describes it as follows:
The comma operator in JavaScript evaluates each of its operands. It returns the value of the last operand. Add multiple expressions using the comma operator.

eval() function in java script throwing error with direct value [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 4 years ago.
I tried to evaluate string function toString() in console.
In one scenario it is working fine and in another scenario it is not working as expected.
Scenario 1:
eval(99.toString());
output:
Invalid or unexpected token ...
Scenario 2:
var a = 99;
eval(a.toString());
Output:
99
Please help me to understand the difference between both the scenarios.
That has nothing to do with eval.
The error is produced by 99.toString. The reason is that 99. is read as a number (equivalent to 99.0) and then toString is just a random word that doesn't fit the syntax:
99.0 toString // what the parser sees
To fix it, you need to keep . from being treated as part of the number. For example:
99 .toString() // numbers can't contain spaces, so '99' and '.' are read separately
(99).toString() // the ')' token prevents '.' from being read as part of the number
99.0.toString() // '99.0' is read as a number, then '.toString' is the property access
99..toString() // same as above, just with '99.' as the number
99['toString']() // using [ ] for property access, no '.' at all
A numeric literall (99) is not and object with properties. A variable with value 99 like var x = 99 is and object and you can use methods like x.toString()
eval expects a script input (string), in example:
var x = eval('var a = 99; a.toString()');
console.log(x);

Is there any reason not to use the plus operator instead of Number() or parseInt() to return a number? [duplicate]

This question already has answers here:
parseInt vs unary plus, when to use which?
(6 answers)
What is the difference between parseInt() and Number()?
(11 answers)
Closed 4 years ago.
Basically, I'm trying to figure out what the difference is between these 3 statements? Is there any reason to use one instead of the others? Is the first one bad practice (it works but I never see it and doesn't seem to be taught anywhere)?
+'21';
Number('21');
parseInt('21');
parseInt parses the string up to the first non-digit number and returns what it found,
For example: parseInt('123abc') // returns 123;
Number tries to convert the entire string into a number if it can.
ForExample: Number('123abc') // returns NaN
Unary plus operator can also be used to convert a string into a number, but it is not very readable when it is being used with other expressions and operators
Internally, +'21' will work in the same way as Number('21') * 1
As far as I know the first two are completely equivalent, and the choice between them is a matter of taste. (Personally I prefer the unary + because it's more concise, and well understood by most JS developers.)
parseInt is different because it reads a number value from the start of the string and ignores the rest when it reaches a non-numeric character. A common use is getting the underlying number from a CSS value like "20px". Note that the other two methods would fail with a NaN in this case.

Unable to convert a string to integer [duplicate]

This question already has answers here:
How can I check if a string is a valid number?
(50 answers)
Closed 4 years ago.
I have an AJAX request in my page and the .php page echoes an integer or string based on the event in the page. But, when the variable reaches to my actual javascript file , it becomes string. For example 4 changes to "4". And that is making my program problematic because my program has to run according to the responseText. I have a XMLHTTPRequestObject.onload function that works like:
if(typeof XMLHTTPRequest.responseText === "number"){
// do something
}
My php script provides a result either integer or string and if the result is string, then I can perform the function but it is not happening like so. I tried changing the variable using parseInt() and Number() but then, everything gets changed to number either it was s string. So, how do I tackle this problem? Please do help!
You can try converting the string to number using Number. If you receive NaN you know the string wasn't a valid number say 123notANumber for example, see here for more information.
if (isNaN(Number('123test')) {
// This is a string
}
else {
// It's a number
}
As mentioned in the comments XMLHttpRequest.responseText will always be a string. The easiest solution is likely to use the Number constructor to convert that string to a number. If the string doesn't represent an integer, Number will return NaN. So instead of what you have currently, you could do somthing like this:
const parsed = Number(XMLHTTPRequest.responseText);
if(isNaN(parsed)){
//handle case where response is a string
} else {
//handle case where response is a number
}

Categories

Resources