validate dynamically generated variable in using javascript - javascript

I have a scenario where i need to check whether a variable is not null using java script
Now these variables can be generated automatically and their naming convention is going to be like below
**Attribute.1.Name='aaa'
Attribute.2.Name='aaa'
Attribute.3.Name=''**
and so on.
how do i validate something like this where i do not now the exact variable name. All i know is the pattern of the variable.
Code example
FunctionName({'Attribute.1.Name':'test','Attribute.2.Name':'test2'});
Thanks

var FunctionName = function(parameters) {
if (parameters['Attribute.1.Name'] == null) {
...
}
}
and if you wanted to loop through all properties of the object:
var FunctionName = function(parameters) {
for (var name in parameters) {
if (parameters.hasOwnProperty(name)) {
if (parameters[name] == null) {
...
}
}
}
}

Related

Can I magically make the selectors non-functional if the selection value is empty?

Background:
I have a function that I call like this:
hide_modules('string1','string2');
The function is something like:
function hide_modules(param1,param2) {
MM.getModules()
.withClass(param1)
.exceptWithClass(param2)
.enumerate(function(module) {
module.hide(
// some other code
);
});
}
Most of the time I call the function with values as shown above.
Sometimes I do not want 'string1' to have a value and I'd like the my function to not use that first selector, effectively like this:
MM.getModules()
// .withClass(param1)
.exceptWithClass(param2)
.enumerate(function(module) {
module.hide(
// some other code
);
});
I've tried just calling it with an empty string, 0, false as param1 but the end result class selection is not what I want.
Sometimes I also call it with param2 empty and not wanting to have the param2 related selector used either.
So the question is:
Without writing a big if-then-else statement, is there some fancy way I can make those selectors non-functional (the equivalent of commenting it out like above) when the param1 and/or param2 values are not specified?
The supporting code that my function calls is provided for me in a 3rd party library that I can't change. I include some of the relevant parts here as it may help with the answer:
var withClass = function (className) {
return modulesByClass(className, true);
};
var modulesByClass = function (className, include) {
var searchClasses = className;
if (typeof className === "string") {
searchClasses = className.split(" ");
}
var newModules = modules.filter(function (module) {
var classes = module.data.classes.toLowerCase().split(" ");
for (var c in searchClasses) {
var searchClass = searchClasses[c];
if (classes.indexOf(searchClass.toLowerCase()) !== -1) {
return include;
}
}
return !include;
});
Since js doesn't supports function overloading, the only way is to validate your parameters inside your method. Check for truthy and ternary operator will do the trick
var modules = MM.getModules();
modules = param1 ? modules.withClass(param1) : modules;
modules = param2 ? modules.exceptWithClass(param2) : modules;
modules.enumerate(function(module) {
module.hide(
// some other code
);
});
to skip first parameter
hide_modules(null,'string2');
to skip second parameter
hide_modules('string1');

Only execute function if value is NOT empty [duplicate]

This question already has answers here:
How to check if a value is not null and not empty string in JS
(11 answers)
Closed 4 years ago.
I have the following html, which is part of a webform:
<input type="hidden" name="userID" id="control_COLUMN43" value="%%userID%%">
The value of this field is dynamically generated by a database. It's possible that the value of this field is empty.
Next to this, I created a function which sends the value of this field (via Ajax) to another database, upon a submit of the webform.
What I want to do now is: only execute this function if the value of the field "userID" is NOT empty. If it's empty, I don't want this function to be executed.
So I assume it will be something like this, but I'm struggling to find the correct way to do this:
if (#control_COLUMN43 !=== "") //this is the id of the field
{
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
Or the other way around I guess?
Can anybody help me with this?
Thanks in advance!
Use like this
// Also u can add null check
if(data !== '') {
// do something
}
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
You should not declare functions inside the conditions. If you do then at the time of execution if the condition is not met, function will not be available which may lead to errors. Hence, you should place the condition inside the function.
You can modify your condition to following
function SendAjax() {
if (document.getEelementById("control_COLUMN43").value) {
//code
}
}
You can access the value of the input by using getElementById(id).value
and declare your function outside the if block like:
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
if (document.getElementById('txt_name').value) //this is the id of the field
{
SendAjax()
}
else
{
//don't execute function
}
The if statement you need, without JQuery, should be like this:
if (document.getElementById("control_COLUMN43").value !=== "") {
// .. commands
}
First get your hidden input value using document.getElementById() and then check if it is null like following:
var userId = document.getElementById("control_COLUMN43");
if (userId) //this is the id of the field
{
SendAjax()
}
else
{
alert("UserId is null);
}
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
In if condition check $("#control_COLUMN43").val()
It can be null or '' so you can apply condition accordingly.
You can check empty value like this
function isEmpty(str) {
return (!str || 0 === str.length);
}
var val = document.getElementById('control_COLUMN43').value;
var col = isEmpty(val);
if (col) {
function SendAjax(){
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
There are several issues at once:
You are mixing up declaring a function with calling it.
To get the value from a control, use document.getElementById("...").value
The proper notation for not === is !==.
This is how it goes:
// Declare the function
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
// Get value
var value = document.getElementById("control_COLUMN43").value;
// Call the function conditionally
if (value !== "")
{
SendAjax();
}
The code you write in if condition is not correct ID value must be get like:
if(document.getElementById("control_COLUMN43").value != ''){
//Your code here
}
Basically you have to check value property of the input element. Using dom selectors first you can select a element using id then you can access value attribute for element. If it's not null or undefined or just empty spaces then you can call your function
function handleClick(){
// Extract value from input element
let val = document.getElementById('input').value;
// Check value is empty or not
if(val){
// If not empty
console.log('Value is : ' + val);
}
else{
// If empty
console.log('Empty input');
}
}
<input id="input" type="text">
<button onclick="handleClick()">SUBMIT</button>
// get the contents of the form element
var control_COLUMN43 = document.getElementById("control_COLUMN43").value;
// process the data
if( control_COLUMN43 != "" ) {......

How to write regular expression to find all function names in a string?

I would like to know writing regular expression for the following string to find all function names.
"var sampleFunc = function(){return 'hello';}alert(sampleFunc());function sampleTest(){var sampleTestVar = 'one';};var sampleFunc = function(){return 'hello';}alert(sampleFunc());function sampleTest(){var sampleTestVar = 'one';};"
The above string contains simple JS program. I would like to get the output for the above string as,
["sampleFunc", "sampleTest", "sampleFunc", "sampleTest"]
Help me in writing regular expression for the above problem.
Ok, here is another approach. In this safer and reliable approach, I used acorn which is a library used by CodeMirror's TernJS for parsing javascript. CodeMirror is a very powerful web-based code editor, used almost everywhere (even here on SO).
The code:
First, here is the code:
HTML:
<script src="path/to/accorn.js"></script>
<script src="path/to/walk.js"></script>
Javascript:
function getFunctionNames(codeString) {
var names = [];
acorn.walk.simple(acorn.parse(codeString), {
AssignmentExpression: function(node) {
if(node.left.type === "Identifier" && (node.right.type === "FunctionExpression" || node.right.type === "ArrowFunctionExpression")) {
names.push(node.left.name);
}
},
VariableDeclaration: function(node) {
node.declarations.forEach(function (declaration) {
if(declaration.init && (declaration.init.type === "FunctionExpression" || declaration.init.type === "ArrowFunctionExpression")) {
names.push(declaration.id.name);
}
});
},
Function: function(node) {
if(node.id) {
names.push(node.id.name);
}
}
});
return names;
}
Example:
function getFunctionNames(codeString) {
var names = [];
acorn.walk.simple(acorn.parse(codeString), {
AssignmentExpression: function(node) {
if(node.left.type === "Identifier" && (node.right.type === "FunctionExpression" || node.right.type === "ArrowFunctionExpression")) {
names.push(node.left.name);
}
},
VariableDeclaration: function(node) {
node.declarations.forEach(function (declaration) {
if(declaration.init && (declaration.init.type === "FunctionExpression" || declaration.init.type === "ArrowFunctionExpression")) {
names.push(declaration.id.name);
}
});
},
Function: function(node) {
if(node.id) {
names.push(node.id.name);
}
}
});
return names;
}
console.log(getFunctionNames(`
var sampleFunc = function() {
return 'hello';
}
/*
function thisIsNotReallyAFunction() {}
*/
alert(sampleFunc());
function /* undesired comment */ sampleTest() {
var sampleTestVar = 'one';
};
var sampleFunc=
// still OK!
function() {
return 'hello';
}
alert(sampleFunc());
function
// all sotrts of comments
sampleTest()
/* Even
* Block ones
*/
{
var sampleTestVar = 'one';
};
var sampleFuncEDIT;
sampleFunEDIT = function (){};
var functionNameEDIT = "sampleFunc";
`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/acorn.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/walk.js"></script>
Explanation:
For a thorough explanation, check out acorn's GitHub page here.
acorn is split into a bunch of source files, each responsible for a specific job. We used only acorn.js and walk.js.
acorn.js is used for parsing. It contains a lot of useful functions used for parsing such as acorn.parse(), acorn.parseExpressionAt(), acorn.tokenizer(), ... We are only interested in acorn.parse which return an AST (abstract syntax tree. Which is basically a tree structure of nodes. A node describes a meaningful chunk of code, it could be of an assignment, a function call, a variable declaration, ... A node will be an object that has properties describing that chunk of code. It will have a type property, a start (where the chunk of code starts), an end (where it ends), and each type of node will have some additional properties only used for that type.
Now, that we have the AST tree, we can walk through it ourselves (they are just a bunch of nested objects anyway). Or use acorn's way: acorn provides us with a very powerful way of walking this tree. The functions are in the file walk.js. Same as acorn.js, walk.js also contain a bunch of useful functions, we only need walk.simple(). What walk.simple does, is that it takes a tree and another object as parameters. The tree is our AST tree (returned by acorn.parse), and the object is an object of this form:
{
[NodeType1]: function(node) { /* node is of type NodeType1 */ },
[NodeType2]: function(node) { /* node is of type NodeType2 */ },
...
}
As walk.simple walks the tree, node by node, it checks if there is a function for the current node's type, if there is one, it will call that function (passing to it the node itself) and proceed to the next node, if not it will ignore the node and proceed to the next node. From the various node types we are only interested in:
Function:
Which is basically a normal function declaration such as:
var codeString = `
function f () {
};
function someName() {
};
() => {
};`;
acorn.walk.simple(acorn.parse(codeString), {
Function: function(node) {
console.log(node);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/acorn.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/walk.js"></script>
Some of the additional properties pairs are: id (which is an identifier node, used for this function declaration, or null if the function doesn't have one). The identifier node, if exist, have a name property, which will be the name of our function.
VariableDeclaration:
Which is any variable declaration using var, let or const:
var codeString = `
var e, f = function() {}, g = () => {};
`;
acorn.walk.simple(acorn.parse(codeString), {
VariableDeclaration: function(node) {
console.log(node);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/acorn.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/walk.js"></script>
This type of nodes will also have some additional properties such as declarations which is an array of all declarations (the example above shows 3: one for e, one for f and one for g). The declarations are also nodes, which have the additional id (the identifier node) and init (the initialization object which is a node describing the value we assign to the variable at initialization or null if it doesn't exist). We are only interested if init.type was a function node (either "FunctionExpression" or "ArrowFunctionExpression").
AssignmentExpression:
Which is any assignment using = (not to be confused with variable initialization):
var codeString = `
someVar = function() {
}
`;
acorn.walk.simple(acorn.parse(codeString), {
AssignmentExpression: function(node) {
console.log(node);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/acorn.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/5.2.1/walk.js"></script>
This node object will have an additional left (left-hand operand) and right (right-hand operand) properties, which are both nodes. We are only interested if the left node was an identifier node and the right node was a function node.
Notes:
acorn.parse throws an error if the actual code string has a syntax error in it. So you may want to wrap its call in a try-catch statement to handle that case, and then pass its result to acorn.walk.simple if only no errors were thrown.
If you don't want to include a type, just remove it from the object and provide only the types you want. Say for example you don't want to include AssignmentExpression, then just remove it from the object passed to acorn.walk.simple
You can have different arrays for different types of functions. Same as of my other answer: varFunctions, functionFunction and assignmentFunctions.
I hope this is helpful and understandable.
First you have to remove undesired comments that may contain confusing content (see the example bellow), then remove all new lines and finally remove block comments. Then you can match the function names. There are two types, ones declared using funcName = function and others declared using function funcName. Both need different regexps.
Working code:
function getNames(text) {
text = text.replace(/\/\/.*?\r?\n/g, "") // first, remove line comments
.replace(/\r?\n/g, " ") // then remove new lines (replace them with spaces to not break the structure)
.replace(/\/\*.*?\*\//g, ""); // then remove block comments
// PART 1: Match functions declared using: var * = function
var varFuncs = (text.match(/[$A-Z_][0-9A-Z_$]*\s*=\s*function[( ]/gi) || []) // match any valid function name that comes before \s*=\s*function
.map(function(tex) { // then extract only the function names from the matches
return tex.match(/^[$A-Z_][0-9A-Z_$]*/i)[0];
});
// PART 2: Match functions declared using: function *
var functionFuncs = (text.match(/function\s+[^(]+/g) || []) // match anything that comes after function and before (
.map(function(tex) { // then extarct only the names from the matches
return tex.match(/[$A-Z_][0-9A-Z_$]*$/i)[0];
});
return {
var: varFuncs,
function: functionFuncs
};
}
var text =
`var sampleFunc = function() {
return 'hello';
}
/*
function thisIsNotReallyAFunction() {}
*/
alert(sampleFunc());
function /* undesired comment */ sampleTest() {
var sampleTestVar = 'one';
};
var sampleFunc=
// still OK!
function() {
return 'hello';
}
alert(sampleFunc());
function
// all sotrts of comments
sampleTest()
/* Even
* Block ones
*/
{
var sampleTestVar = 'one';
};
var sampleFuncEDIT = function (){};
var functionNameEDIT = "sampleFunc";
`;
var names = getNames(text);
console.log(names);
Notes:
Function names can contain various other unicode characters that can't be matched using the above regex [$A-Z_][0-9A-Z_$]*. ECMA Specs.
Even if we remove the comments, there could be other factors that may confuse the function (for example strings). The above presents a simple use case, if you are looking for an advanced way of doing this then you need to parse the string, not use regexes.
Here are some examples where the function won't work:
var text = "var dummyString = 'function thisShouldntBeMatchedButWillBe';"
var text = "someString = 'this /* will confuse the comment removal'";
// ...
var re=/(\w+)\(\)/g
// var re=/([\w_-]+)\(\)/g
var rslt = s.match(re)
Still keep it simple.

AngularJS setting up a function to prevent duplication

At the moment I have duplicate code where I have the following examples:
if ($scope.user.window.title == 'true'){
if (this.title){
title = '<h2>'+this.title+'<h2>';
} else {
title = '';
}
} else {
title = '';
}
if ($scope.user.window.football == 'true'){
if (this.football){
football = '<p>'+this.football+'<p>';
} else {
football = '';
}
} else {
football = '';
}
I have tried the following but it doesn't work, it says that the $scope.user.window.football and $scope.user.window.title don't exist. I think it is down to the below function sending the value through as a string for my $scope.
function CheckWindow(element,tag) {
console.log(element);
if ($scope.user.window.element == 'true'){
if (this.element){
element = '<'+tag+'>'+this.element+'</'+tag+'>';
} else {
element = '';
}
} else {
element = '';
}
}
Usage
CheckWindow('title','h2')
CheckWindow('football','p')
$scope.user.window.element tries to access the property named element of $scope.user.window. You need $scope.user.window[element] instead.
this refers to the created function's scope. You could pass a new argument that for example.
that.element will have to be rewritten to that[element], for the same reason as in #1.
You can't assign a new value to a function's parameter (well, you can, but it won't be accessible outside the function's scope). Better return the value.
So:
function CheckWindow(that, element, tag) {
if ($scope.user.window[element] && that[element]){
return '<'+tag+'>'+that[element]+'</'+tag+'>';
}
return '';
}
title = CheckWindow(this, 'title', 'h2');
football = CheckWindow(this, 'football', 'p');
try
$scope.user.window[element]
When you need to reference a property as a sttring, you must use bracket notation.
Also, I doubt that 'this' will reference what you want. You may need to angular.bind this to the method.

How to declare a global variable in Javascript using Jquery

Js file inside I have a function with a particular algorithm.
For reading xml file and transform the data to variable name wordData.
Inside the function has the following line of code:
var wordData = xhr.responseXML.getElementsByTagName (Node1);
I can not set the variable "wordData as a global" outside the function or global
Inside the function
function language() {
lang = "heb";
if (lang == "heb") {
thisWord = wordArrayHeb[indeXML];
}
else {
thisWord = wordArrayEng[indeXML];
}
alert("language thisWord:=" + thisWord);
}
function setWord() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var wordData = xhr.responseXML.getElementsByTagName(Node1);
XMLength = wordData.length;
for (i = 0; i < XMLength; i++) {
wordArrayHeb[i] = wordData[i].getElementsByTagName(Node2)[0].firstChild.nodeValue;
wordArrayEng[i] = wordData[i].getElementsByTagName(Node3)[0].firstChild.nodeValue;
}
language();
}
}
}
}
the variable thisWord is effected from varible wordData which is not global.
Outside the functions, varible thisWord is empty
inside the function is ok and it has a value.
Would love help.
Thank you!
Simply declare
var wordData;
outside the function and change your line to:
wordData = xhr.responseXML.getElementsByTagName (Node1);
Hence removing the var declaration.
You can create a global var anywhere in JS by using the window object:
window['wordData'] = xhr.responseXML.getElementsByTagName(Node1);
or
window.wordData = xhr.responseXML.getElementsByTagName(Node1);
Then wordData can be accessed globally. This may not be the best solution for your problem, consider using function arguments and return values instead.
i think setting it as a global var is not the best choice, if you wish to access wordData inside the function language, you should pass it as a parameter like so:
language(wordData);
and in declaring function language(), just make it so it accepts the parameter:
function language(wordData) {
...
}

Categories

Resources