RegEx how to use correctly to check str - javascript

Trying to use RegEx but doesn't work...what i've missed?How to alert message when it is "/0" in my calculator?
function div(input)
{
var input = document.getElementById("t").value;
var is_div_by_zero = /\/[\s.0]+$/.test(input);
if (is_div_by_zero)
{
alert(" / to Zero");
}
}

No need to do this with a regex, check the number value instead. E.g.
if (!Number(document.getElementById("t").value)) {
alert("Division by zero")
}
This will cast the value as a number and, when casted to a boolean, check if it's truthy or not. E.g. the value '1' will be casted to 1 which is true whereas 0 is false and 'foo' is NaN which is false.

Related

How to test if a string is a not number

I'm trying to verify if a string is text or number.
Could not find a proper way to verify.
Could you please advice?
Here is my problem:
var myNumber = "006";
var myText = "1. This is not a number";
isNaN(myNumber); // false
isNaN(myText); // false
I tried also:
isNaN(myNumber.split('.')[1]); // true
isNaN(myText.split('.')[1]); // true
parseInt(myNumber); // 6
parseInt(myText); // 1
What I would like to achieve would be to find when a string can be converted to a number (see myNumber). In case that the string is actually a text, how to spot it with javascript?
Could you please advise?
If I understood your question correctly I may have a solution but this will work even if the string is a number so here you go:
var yourNumber="55";
if(yourNumber*1==yourNumber){
alert("It's a number");
}else{alert("it's not a number");}
If parseInt() is not working for your desired results, you can try Number constructor. It gives you NaN for non-numbers, which you can verify by using isNaN() function.
var myNumber = "006";
var myText = "1. This is not a number";
console.log( Number(myNumber) );
console.log( Number(myText) );
Or you can use regular expressions:
var myNumber = "006";
var myText = "1. This is not a number";
var numRegex = /^\d+$/;
console.log( numRegex.test(myNumber) );
console.log( numRegex.test(myText) );
You can use regex.
function isNumber(num){
return /^(\d+)?(\.)?\d+$/.test(num);
}
isNumber("006") // true
isNumber(".6") // true
isNumber("1 not a number") // false
isNumber("23.63") // true
isNumber("23.6.3") // false
You can check if text is a number using isNaN function:
var myNumber = "006";
var myText = "1. This is not a number";
console.log(myNumber + ': ' + !isNaN(myNumber));
console.log(myText + ': ' + !isNaN(myText));
var reg = new RegExp('^[0-9]*$');
var myNumber = "006";
var myText = "1. This is not a number";
reg.test(myNumber) //true
reg.test(myText) //false
The short story:
I would really use the typeof operator.
From isNaN() | JavaScript MDN:
The isNaN() function determines whether a value is Not-A-Number or not. ... you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.
Long story:
Tried the following in a node console.
A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
isNaN(123) // false
isNaN(true) // false
isNaN("123") // false
isNaN({}) // true
isNaN(undefined) // true
In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.
Number.isNaN(undefined) // false
Number.isNaN({}) // false
Number.isNaN(true) // false
Number.isNaN(123) // false
Number.isNaN(NaN) // true
Number.isNaN(0/0) // true
The typeof operator returns a string indicating the type of the unevaluated operand.
typeof(123) // number
typeof("123") // string
typeof(true) // boolean
Generally, the isNaN is the right idea, but you should parse it first:
var myNumber = "006";
var myText = "1. This is not a number";
Number.isNaN(Number.parseInt(myNumber)); // false
Number.isNaN(Number.parseInt(myText)); // true

Check if string zero, zero, empty string, null

in PHP:
$var=0;
$var="";
$var="0";
$var=NULL;
to verify if $var is 0 or "0" or "" or NULL
if (!$var) {...}
in jQuery/JavaScript:
$var=0;
$var="";
$var="0";
$var=NULL;
if (!$var) works for every value except for "0"
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
No. In PHP, the values converted to booleans produces different results than in JavaScript. So you can't do it exactly like PHP does.
Why not be (a bit more) explicitly about it which makes your code easier to understand?
// falsy value (null, undefined, 0, "", false, NaN) OR "0"
if (!val || val === '0') { }
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object true
0 will return false.
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Number(variable) seems to produce expected output
Number(0) = 0
Number("0") = 0
Number("") = 0
Number(null) = 0
Number(false) = 0
If you feel funky (just in your exact case-sample) you can do this:
(otherwise undefined and NaN will result as false)
+v===0
Example:
var a = [0, "", "0", null];
var b = [1, "a", "1", {}];
a.forEach(function(v){
console.log( +v===0 ); // true, true, true, true
});
b.forEach(function(v){
console.log( +v===0 ); // false, false, false, false
});
First of "0" isn't false, its true. Because '0' is a string. Strings if they exist return true. So
!"" should return false. That said if your data is returning zeros as strings you can use:
parseInt("0", 10);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This will return the integer value or NaN.
!NaN will return true, and if it is an number of say... 0 it will return !0 so you could do this:
function nullOrEmpty(value) {
return (!value && !parseInt(value));
}
You could very well use a double negative.
var test = 0;
console.log(!!test);
var test = "";
console.log(!!test);
var test = "0";
console.log(!!test);
var test = null;
console.log(!!test);
Although "0" is not an empty string so it evaluates to true, the rest return false.
Also, I agree with the comment that dfsq made in that you shouldn't rely on this. You should know and understand what types your variables are holding.

Javascript RegEx.Test always returning true

I have a value in a text input I need to verify as a date in the format dd/mm/yyyy. Below is my code. I always get true regardless of what I enter in the text input. Otherwise function works well. Always displays an alert with the value I put in the text input.
function checkDate(date)
{
var result;
var expression = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
result = expression.test(date.value);
if(result=true)
{
alert(date.value);
}
else
{
alert("false finally");
}
}
if(result==true)
{
alert(date.value);
}
instead having single "=" have "==" , else you can use like this
if (result)
{
alert(date.value);
}
and always remember this
"1" == 1 // true
"1" === 1 // false
An example of type coercion at work. Basically anytime your value is the "same" but the type isn't then == works.
Please use === everywhere. There's no need to use ==. checking for types is always better. If something breaks then you can convert from type a to type b

Checking only the integer values through Regex

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

Integer validation not working as expected

Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.

Categories