Javascript isnull - javascript

This is a really great function written in jQuery to determine the value of a url field:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
// example.com?someparam=name&otherparam=8&id=6
$.urlParam('someparam'); // name
$.urlParam('id'); // 6
$.urlParam('notavar'); // null
http://snipplr.com/view/11583/retrieve-url-params-with-jquery/
I would like to add a condition to test for null, but this looks kind of klunky:
if (results == null) {
return 0;
} else {
return results[1] || 0;
}
Q: What's the elegant way to accomplish the above if/then statement?

return results == null ? 0 : (results[1] || 0);

return results == null ? 0 : ( results[1] || 0 );

the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.

You could try this:
if(typeof(results) == "undefined") {
return 0;
} else {
return results[1] || 0;
}

return results==null ? 0 : ( results[1] || 0 );

return (results||0) && results[1] || 0;
The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.

if (typeof(results)!='undefined'){
return results[1];
} else {
return 0;
};
But you might want to check if results is an array. Arrays are of type Object so you will need this function
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
So your code becomes
if (typeOf(results)==='array'){
return results[1];
}
else
{
return 0;
}

All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:
//function that checks if an object is null
var isNull = function(obj) {
return obj == null;
}
if(isNull(results)){
return 0;
} else {
return results[1] || 0;
}
Using the isNull function helps the code be more readable.

I prefer the style
(results || [, 0]) [1]

Why not try .test() ? ... Try its and best boolean (true or false):
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)');
return results.test(window.location.href);
}
Tutorial:
http://www.w3schools.com/jsref/jsref_regexp_test.asp

I'm using this function
function isNull() {
for (var i = 0; i < arguments.length; i++) {
if (
typeof arguments[i] !== 'undefined'
&& arguments[i] !== undefined
&& arguments[i] != null
&& arguments[i] != NaN
&& arguments[i]
) return arguments[i];
}
}
test
console.log(isNull(null, null, undefined, 'Target'));

You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.
For example:
var pass = "";
if(!pass)
return false;
else
return true;
This would return false because the string is empty. It would also return false if the variable pass was null.

Related

How to implement this test on prototype of String object?

How to implement this valid function?
I want to implement a test function that returns true or false,
example : 'any-string-1'.valid('!empty'):
this is my valid.js file
function valid(str) {
if (
typeof str == "undefined" ||
!str ||
str === "" ||
str.length < 10 ||
!/[^\s]/.test(str) ||
/^.*-s/i.test(str)
) {
return true;
} else if (str.length > 30) {
return false;
}
}
module.exports = valid;
Assuming you are using Jest, you can use toBe:
const emptyStr = '';
const str = 'some-str';
expect(Boolean(emptyStr.length)).toBe(false); // it's empty, it's false because length is 0;
expect(str.length > 30).toBe(false); // it's false because length is not greather than 30;
expect(str.length < 10).toBe(true); // it's true because length is lower than 10;

Iteration through string and remove all instances of

My instructions were to iterate through a string and remove all instances of the letter "a". I thought that it would be easy to find examples, but I was unable to do so. Some would remove the letter without the iteration, but that is not what the instructions asked. If someone could please look at my code and assist me in my task I would greatly appreciate it! The "removeA" function will iterate through the string now, and only console logs the !== "a", but for the life of me I can't figure out how to save it to a new string. Thanks in advance.
removeA = function(stringWithA) {
if (stringWithA === null || typeof (stringWithA) !== "string" || stringWithA === "") { //Checking for is null AND is not array
return 'Please enter a valid string';
} else {
lowerWithA = stringWithA.toLowerCase();
for (var i = 0; i < lowerWithA.length; i++) {
if (lowerWithA.charAt(i) !== "a") {
console.log(lowerWithA.charAt(i));
}
}
}
}
You can store the letters into an Array.
var removeA = function(stringWithA) {
if (stringWithA === null || typeof(stringWithA) !== "string" || stringWithA === "") { //Checking for is null AND is not array
return 'Please enter a valid string';
} else {
var newString = [];
lowerWithA = stringWithA.toLowerCase();
for (var i = 0; i < lowerWithA.length; i++) {
if (lowerWithA.charAt(i) !== "a") {
newString.push(lowerWithA.charAt(i))
}
}
return newString.join('');
}
}
console.log(removeA("Eleazar"))
Or, just use a regex:
var removeA = function(stringWithA) {
if (stringWithA === null || typeof(stringWithA) !== "string" || stringWithA === "") { //Checking for is null AND is not array
return 'Please enter a valid string';
} else {
return stringWithA.replace(/a/gi, '')
}
}
console.log(removeA("EleaaaaazAreeeeaaaElAAAAAeaaaEleEvene"))
Why not build a new string with all the characters that are not a?
var newString = "";
for (var i = 0; i < lowerWithA.length; i++) {
var letter = lowerWithA.charAt(i);
if (letter !== "a") {
newString += letter;
}
}
console.log(newString);
If you wanted to expand this to be case-insensitive:
...
if (letter !== 'a' || letter !== 'A') { ... }
And simply don't call String.toLowerCase() on the original string.
I suppose there's already a function that you need, replace:
var stringWithA = 'A aaaa bbbcc!';
alert(stringWithA.replace(/[Aa]/g, ''));

Cannot read property length null error when used with regular expressions

I'm a javascript beginner doing some CodeWars.com questions. I came across this question and I'm stuck due to a "cannot read property length null" error. I've tried to look up that error and can't find what the problem is in my program.
The assignment is:
"Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contains any char."
And this is what I've written so far:
function XO(str) {
var x = "x";
var o = "o";
var numX = str.match(/x/gi).length;
var numO = str.match(/o/gi).length;
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
if (numX === -1 && numO === -1){
return true;
}
}
XO("xoxo");
The assignment also says that if there is neither an X or an O then the program should return true.
This will not give you that error. When there are no matches, the match function returns null and you cannot get the length of null. A few extra lines solves this issue.
function XO(str) {
var x = "x";
var o = "o";
var numX = 0;
var numO = 0;
var xMatch = str.match(/x/gi);
var oMatch = str.match(/o/gi);
if (xMatch) {
numX = xMatch.length;
}
if (oMatch) {
numO = oMatch.length;
}
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
} else {
return false;
}
}
if (numX === -1 && numO === -1){
return true;
} else {
return false;
}
}
console.log(XO("ddd"));
I think you are making this problem more complex than it has to be.
All you need to do is make the string lowercase(to account for case insensitive), traverse the string, and when it finds an x, add 1 to a counter, and when you find and o, decrease 1 from the counter.
If it ends at 0, you return true, else you return false. There's no need for regexes
function XO(str){
var count = 0;
str = str.toLowerCase();
for(var i = 0; i < str.length; i++){
if(str[i] === 'x') count++;
if(str[i] === 'o') count--;
}
return count === 0 ? true : false;
}
Yes you have to check the return value of match is not null before checking the length property. However
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
looks like an infinite loop if either string contains lower case 'x' or 'o' and there are a different number of each.
More simply:
function XO(str)
{ var matchX = str.match(/x/gi);
var matchY = str.match(/o/gi);
return (matchX && matchY) ? matchX.length == matchY.length : !matchX && !matchY;
}

How to catch null, undefined, blank values with AngularJS filter

I'm attempting to write a filter for use in a grid that will catch all null, undefined, blank string, or other similar values and display a dash "-". I've written the following so far, but it doesn't catch null values, and I'm wondering if it could be more succinct and possibly refactored to avoid three layers of nested if/else statements. Percentage values need to be checked that they're over 0 and under 1. Also, negative numbers and 0's should be returned as is. Thanks!
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (cellFilter == undefined) {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
}
}
};
});
Version 2.0 taking into account #tymeJV's comment:
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (!cellFilter) {
return (angular.isNumber(input) || (input)) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || (input)) ? $filter(cellFilter)(input, args1, args2) : '-';
}
}
};
});
Whenever you encounter a function that's getting too complex to refactor try extracting some of the smaller statements to concisely named variables. It makes it much easier for our brains to keep track of the function's requirements, and it's also more readable to new devs reading your code.
var inputHasValue = angular.isNumber(input) || input;
if(!inputHasValue){
return '-';
}
if (!cellFilter) {
return input;
}
var isPercentageCell = cellFilter.match(/pctg|percent|pctgFilter|incidence/ig);
var valueIsInRange = input > 0 && input < 1;
if(!isPercentageCell || valueIsInRange){
return $filter(cellFilter)(input, args1, args2);
}
return '-';
typeof x ==='number' || !!x
is false when x is null, undefined or empty string
Only one case in which it doesn't work – if you need to filter boolean variables, but your case doesn't seem to need it.
Anyway in that case you can use
typeof x === 'boolean' || typeof x ==='number' || !!x

How Set local storage to 0 if undefined?

if localStorage["BestScore"] = undefined;
{
localStorage["BestScore"]=0;
maxScore=0;
}
var maxScore=localStorage["BestScore"];
var newScore=false
function drawScore(score) {
if (newScore == true && score < maxScore) {
newScore = false;
}
if (score > maxScore) {
newScore = true;
localStorage["BestScore"] = score;
if ([5, 10, 15, 20].indexOf(score) !== -1) {
play(sndMedal);
} else {
play(sndGain);
}
}
This code is to set the max score and then store it but it doesn't seem to set the local storage to 0 if undefined.
if localStorage["BestScore"] = undefined;
should be:
if( typeof localStorage["BestScore"] === 'undefined' )
However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:
if (typeof localStorage["BestScore"] === "undefined") {
localStorage["BestScore"] = 0;
}
It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.
if localStorage["BestScore"] = undefined;
should be ==
else you are assigning, not comparing.
use == or === as a comparison operator, then it should be fine

Categories

Resources