function isBlank(s){
var len = s.length
var i
for(i=0; i<len; ++i) {
if(s.charAt(i)!= " ") return false
}
return true
}
I am totally new to JavaScript and coding. Please can someone explain me how is this code working.
I know that it is being used to check whether a input box has some value or not, but I know no further.
question update....
See, in the above code, the for loop runs and if the string is not blank it returns false.
Now for loop ends and browser reads the next line which is-- returns true--. So is not the function finally returning true. No matter if there was a return false in the middle.
It is looping through the string s and checking if each character is a space. If there are characters other than spaces, then the function returns false, because the string is not blank. If the string is empty or only contains spaces, then it returns true because the string is blank.
function isBlank(s){ // it is a function named 'isBlank' that accept one parameter, that the parameter is something passed from the outside
var len = s.length // Assign the length of parameter 's' into a local variable 'len'
var i // Declare a new local variable 'i'
for(i=0;i<len;++i) { // This is a 'loop', you can google it
if(s.charAt(i)!= " ") return false // if any character inside the parameter 's' is not an empty space, that means it isn't blank, so return false
}
return true; // If code reach this line that means 's' is either with 0 length or all characters of it are an empty space
}
By using the above function:
alert(isBlank("123")); // false
alert(isBlank("")); // true
alert(isBlank(" ")); //true
The function checks whether the string is empty or not.
for(i=0;i<len;++i) { // iterates through the string
if(s.charAt(i)!= " ") // checks whether character at index i of string s is not equal to " ".
return false
}
It iterates through the string and returns false if any character is not equal to " ".s.charAt(i) returns the character at index i of the string s.
If the condition is not satisfied for every character then it returns true.
Related
Today when I was doing some experiments with ==, I accidentally found out that "\n\t\r" == 0. How on earth does "\n\t\r" equal to 0, or false?
What I did is:
var txt = "\n"; //new line
txt == 0; //it gives me true
And that really annoy me. So I did more:
var txt = "\r"; //"return"
txt == 0; //true
var txt = "\t"; //"tab"
txt == 0; //true
It does not make sense, at all. How's that happen? And more crazy is this:
//Checking for variable declared or not
var txt ="\n\t\r";
if(txt!=false){
console.log("Variable is declared.");
}else{
console.log("Variable is not declared.");
}
What it gives me is Variable is not declared.
How is it equal to 0, or false???
This behaviour might be surprising but can be explained by having a look at the specification.
We have to look at the what happens when a comparison with the equals operator is performed. The exact algorithm is defined in section 11.9.3.
I built a simple tool to demonstrate which algorithm steps are executed: https://felix-kling.de/js-loose-comparison/
string == integer
The step we have to look at is #5:
5. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.
That means the string "\n" ("\r", "\t") is converted to a number first and then compared against 0.
How is a string converted to a number? This is explained in section 9.3.1. In short, we have:
The MV (mathematical value) of StringNumericLiteral ::: StrWhiteSpace is 0.
where StrWhiteSpace is defined as
StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpace_opt
StrWhiteSpaceChar :::
WhiteSpace
LineTerminator
This just means that the numerical value of strings containing white space characters and/or a line terminator is 0.
Which characters are considered as white space characters is defined in section 7.3.
string == boolean
The step we have to look at is #7:
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
How booleans are converted to numbers is pretty simple: true becomes 1 and false becomes 0.
Afterwards we are comparing a string against a number, which is explained above.
As others have mentioned, strict comparison (===) can be used to avoid this "problem". Actually you should only be using the normal comparison if you know what you are doing and want this behaviour.
Because JavaScript is a loosely typed language, it attempts to type cast your 1st side of the comparison to the other so that they would match each other.
Any string which does not contain a number, becomes 0 when compared to an integer, and becomes true (Except in certain situations), when compared to a Boolean.
Light reading material.
txt is not a Boolean, so it will never be false. It can be undefined though.
var txt ="\n\t\r";
if(txt !== undefined) { //or just: if (txt)
console.log("Variable is declared.");
} else {
console.log("Variable is not declared.");
}
//=> will log: 'Variable is declared.'
By the way, a declared variable may be undefined (e.g. var txt;).
If you do a stricter comparison (without type coercion, using ===), you'll see that
var txt = '\n'; txt === 0; //=> false
var txt = '\r'; txt === 0; //=> false
var txt = '\t'; txt === 0; //=> false
See also
The reason is that "\n\t\r" just as " " are treated as empty strings.
If you use == it will return true but if you use === it will return false.
If you want to test for existence you should use something like
if(typeof strName !== 'undefined') {
/*do something with strName*/
} else {
/*do something without it*/
}
Whenever you use the == operator and try to compare a string to a number, the string will first be converted to a number. Thus: alert("\n\r"==0) becomes: alert(Number("\n\r")==0)
The Number constructure is kind of interesting. It will first strip whitespace then decide if the number is a not a number or not. If NaN, then the result is "NaN". If the string is empty, then the result is 0.
alert(Number()) alerts 0
alert(Number("")) alerts 0
alert(Number(" \n \r \n \t")) alerts 0
alert(Number("blah")) alerts NaN
alert(Number("0xFF")) alerts 255
alert(Number("1E6")) alerts 1000000
To check if the result is NaN use isNaN()
Thus: alert(isNaN("blah")) alerts true
Thus: alert(isNaN("")) alerts false
Thus: alert(isNaN("\n")) alerts false
Thus: alert(isNaN(" ")) alerts false
however do note that NaN will never equal NaN:
var nan=Number("geh");alert(nan==nan); alerts false
Update:
if you want to check if both sides are NaN, then you'd convert both to boolean values first like so:
var nan=Number("geh");alert(!!nan==!!nan); alerts true
or better yet
var nan=Number("geh");
alert(isNaN(nan)&& isNaN(nan));
I want to write a program in JavaScript for password strength calculator so i need 3 function.
One function tells whether the varaible passed has Alphabet or not and same check for Numeric and Characters
var = 'abc123'
function alpha(var) {
// Should return true if variable includes alphabet and false if not
}
function Num(var) {
// Should return true if variable includes Numeric value and false if not
}
function SpecialChar(var) {
// Should return true if variable includes any Special Character and false if not
}
I have tried this method
var password = 'abc123'
function alpha() {
return password.match(/^[a-zA-Z- ]+$/) ? true : false
}
function num() {
return password.match(/^[0-9]+$/)
}
but this not works as i want
Instead of match i suggest using test it will return true or false based on the given expression.
Second of all you are using ^ and $ which mean the start and end of the string. If you remove them your regex works. The reason we don't need them is because right now you're saying "I need atleast one alphanumeric character between the start and the end of the string, nothing else". Same goes for the second function but then with numbers instead of alphanumeric characters
var password = 'abc123'
function hasAlpha(str){
return /[a-zA-Z- ]+/.test(str);
}
function hasNum(str){
return /[0-9]+/.test(str);
}
console.log(hasAlpha(password));
console.log(hasNum(password));
what if you try following regex instead ?
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})/
this will match for password strength which i guess you are looking for.
Pardon if this question has already been answered however I'm struggling to find the any answers to it.
I'm looking to see if I can convert variable types to a string in the code below.
input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)
i.e. if the user were to type 1 typeof would return number, or if the user were to enter true it would return a boolean
You can run the input through a series of parseInt, parseFloat and
parseBool
functions.
Whenever you get a valid result, return it.
Something similar to:
if (parseInt(input) != NaN) {
return "int"
}
if (parseFloat(input) != NaN) {
return "float"
}
Generally, all inputs per your example will return a string careless of what they entered or intended to enter. We could however build a few logics to check if what they entered is; Strings (Alphabets only) or an integer (numbers only) or any other ones per a few other logics you could base your checks on.
One of the quickest ways to check if an input contains a number or not;
isNaN(input) // this returns true if the variable does NOT contain a valid number
eg.
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
you could try regex (which is not always ideal but works)
var input = "123";
if(num.match(/^-{0,1}\d+$/)){
//return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
//return true if float
}else{
// return false neither worked
}
You could also use the (typeof input) but this will be more convenient if your user is going to enter an expected set of entries
var input = true;
alert(typeof input);
// This eg will return bolean
Let me know if this helps.
I would like to sum the args of my function if and only if the two args are numbers (hence my first function).
function checkNum() {
var num = 0;
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] !== 'number') {
return false;
}
}
return true;
}
function addTogether() {
var num = 100;
if ( checkNum() ) {
return arguments[0] + arguments[1];
} else {
return undefined;
}
}
addTogether(2, "");
However my second function performs the sum no matter what the args values are. Any hints on how to fix this ?
checkNum() isn't declared to explicitly take any arguments (which implies to anyone looking at the function that none are expected) and you are not sending any when you call it, so arguments.length is always 0, you never enter into your loop body and you always return true.
Your second function is called by passing two arguments, so your references to arguments[0] and arguments[1] are valid there. But, even still, the use of arguments isn't really meant for all argument passing.
It's best to set up your functions with named parameters and then you can access them via those names. The use of arguments (while valid), is not encouraged as the default mechanism for accessing arguments. It's generally used for validation (ensure that the correct amount of parameters were passed to the function before the function attempts to operate on them, for example).
Also, it's best to test for numbers with a regular expression because typeof can "lie" to you. For example:
// Would you ever think that not a number is of type "number"?!
console.log(typeof NaN === "number");
Now, depending on your criteria for "number", there are two ways you could go.
Only numeric digits are allowed (i.e. 6 is allowed, "6" is not)
// It's better for this function to test one number
// at a time, so you can react to that particular
// success or failure
function checkNum(num) {
// No loop and no if/then needed, just return
// whether the argument is a number, but don't
// test for typeof number because typeof NaN === "number"
// Use a regular expression instead
var reg = /[0-9]+$/; // digits or strings of characters that are from 0 - 9
// Test for only digits not numbers passed as strings
// For example 6 is good, "6" is bad. Here, the use of "typeof"
// is safe because you are also testing that the input is digits
// or characters from 0 to 9 (NaN wouldn't pass this test)
return reg.test(num) && typeof num === "number"; // true or false will be returned
}
function addTogether(val1, val2) {
// Test each input, independantly so that you can react more granularly
if ( checkNum(val1) && checkNum(val2) ) {
return val1 + val2;
}
// It's not necessary to have an "else" that returns undefined because
// that's what will happen as long as you don't return anything else.
}
console.log(addTogether(2, "")); // undefined
console.log(addTogether(2, 6)); // 8
console.log(addTogether(2, "6")); // undefined because "6" is a string, not a digit
Numeric digits and numeric characters are allowed (i.e. 6 and "6" are allowed). In this case, you'd need to ensure that numeric characters get converted to numbers before addition is done so you get mathematical addition and not string concatenation.
// It's better for this function to test one number
// at a time, so you can react to that particular
// success or failure
function checkNum(num) {
// No loop and no if/then needed, just return
// whether the argument is a number, but don't
// test for typeof number because typeof NaN === "number"
// Use a regular expression instead
var reg = /[0-9]+$/; // digits or strings that are from 0 - 9
// Test for only digits and numbers passed as strings
return reg.test(num); // true or false will be returned
}
function addTogether(val1, val2) {
if ( checkNum(val1) && checkNum(val2) ) {
// If checkNum returns true for numeric characters as well as digits, then
// you'd need to ensure that the characters get converted to numbers so that
// you get mathmatical addition and not string concatenation. That would be done like this:
return +val1 + +val2
}
// It's not necessary to have an "else" that returns undefined because
// that's what will happen as long as you don't return anything else.
}
console.log(addTogether(2, "")); // undefined
console.log(addTogether(2, 6)); // 8
console.log(addTogether(2, "6")); // 8 because "6" is converted to 6, not a string of "6"
The arguments array, as evaluated within checkNum, contains the arguments passed to checkNum. But you aren't passing any arguments to checkNum. Try changing the if statement to
if ( checkNum(arguments[0], arguments[1]) )
You aren't passing any arguments to checkNum. You can fix this with apply:
// ...
if (checkNum.apply(this, arguments)) {
// ...
Edit: That would allow you to check any number of arguments passed to addTogether. If you only want to allow for two arguments, you can used named parameters:
function checkNum(a, b) {
return typeof a === 'number' && typeof b === 'number';
}
function addTogether(a, b) {
if (checkNum(a, b)) return a + b;
else return undefined; // line not needed
}
addTogether(2, "");
I have a check on submit to validate some fields and I need to check for only numbers and dashes:
var numPattern = /^[0-9\-]+$/;
//UI field null check
if (ssn != (numPattern.test(ssn))) {
displayError(Messages.ERR_TOPLEVEL);
}
if (accntNoCL != (numPattern.test(accntNoCL))) {
displayError(Messages.ERR_TOPLEVEL);
}
This is not working for some reason. Any ideas why that is?
The regex.test() function, or numPattern.test() in your case, returns a boolean true/false result.
In your code, if (ssn != numPattern.test(ssn)), you're checking if the result is equal to the value you're testing.
Try changing it to the following:
if (!numPattern.test(ssn)) {
test is a predicate, it returns a boolean:
var numPattern = /^[0-9\-]+$/;
numPattern.test("hello, world!"); // false
numPattern.test("123abc"); // false
numPattern.test("123"); // true
numPattern.test("12-3"); // true
test returns a boolean, not a match. Simply use
if (!numPattern.test(ssn)) {
displayError(Messages.ERR_TOPLEVEL);
}
if (!numPattern.test(accntNoCL)) {
displayError(Messages.ERR_TOPLEVEL);
}
If you ever need a match, use either the match function of strings or the exec function of regex objects.