Alternative to eval [duplicate] - javascript

This question already has answers here:
Alternative to eval() javascript [duplicate]
(6 answers)
Closed 9 years ago.
I am making some common function where in I pass the array, name of field from array, value of field in array and return field name to return value as below
function arrayFilter(_array, findField, value, returnField) {
var temp = "_array[i]." + findField;
var retValue = "";
for (var i = 0; i < _array.length; i++) {
if (eval(temp) == value) {
return eval("_array[i]." + returnField);
}
}
}
But when I read on Internet I found that eval is not good, it can have string injection attack.
So somebody help on above.

Instead of:
return eval("_array[i]." + returnField);
Try:
return _array[i][returnField];
And also read this article.

You can use the square bracket notation for accessing properties when the value of your key is unknown.
function arrayFilter(_array, findField, value, returnField) {
var temp = _array[i][findField];
var retValue = "";
for (var i = 0; i < _array.length; i++) {
if (temp == value) {
return _array[i][returnField];
}
}
}

Related

Check if string contains any of array of strings without regExp [duplicate]

This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 5 years ago.
I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.
Can anyone break my code down why it is not working properly?
function checkInput(input, words) {
var arr = input.toLowerCase().split(" ");
var i, j;
var matches = 0;
for(i = 0; i < arr.length; i++) {
for(j = 0; j < words.length; j++) {
if(arr[i] == words[j]) {
matches++;
}
}
}
if(matches > 0) {
return true;
} else {
return false;
}
};
checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"])); // returns false; should be returning true;
Thank you for your time!
You can use functional methods for this. Try Array.some.
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
You can use array#includes to check if a word exist in your input and convert both your input and words in lower case and then use array#includes.
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
You can create regular expression and use i flag to specify case-insensitivity
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));

Javascript .split () function with multiple conditions [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 6 years ago.
Hey there I am having some troubles working with the split function within GTM, I want to read the body class and return a singular word. e.i.
<body class="landing-holidays subscribe-page"></body>
Returning just 'holidays', my challenge is to get the split to just pull the second value. Code:
function () {
var product = document.getElementsByTagName('body')[0];
if (product != undefined) {
var product_id = product.getAttribute('class');
if (product_id != null)
return product_id.split('-')[1];
}
return null
}
I get "holidays subscribe". When I need "holidays", any insight?
You can use a regular expresion. change .split('-') to .split(/[\-\s]/)
var product = document.getElementsByTagName('div')[0];
function run() {
if (product != undefined) {
var product_id = product.getAttribute('class');
if (product_id != null) {
var a = product_id.split(/[\-\s]/);
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] === 'holidays') {
return a[i];
}
}
}
}
}
alert(run())
<div class="landing-holidays subscribe-page"></div>

Print all the names of keys stored in localStorage html [duplicate]

This question already has answers here:
Get HTML5 localStorage keys
(15 answers)
Closed 7 years ago.
I'm trying to print the names of all the keys stored in localStorage with each key in a separate line. This is my code:
function viewsaved(){
$('#saved').show();
var stuffsaved = Object.keys(localStorage);
var splitit = stuffsaved.split(',');
for (var i = 0 ; i < splitit.length ; i++ ){
$('#saved').append(splitit[i]+"<br>");
}
}
when I call the function, it does nothing.
How do you do this properly?
Object.keys returns an array, not a string. Just modify slightly:
var stuffsaved = Object.keys(localStorage);
for (var i = 0 ; i < stuffsaved.length ; i++ ) {
$('#saved').append(stuffsaved[i]+"<br>");
}
If you have or expect a lot of keys, I would suggest building the list in a temporary variable first to avoid frequent DOM update, for example:
var keys = Object.keys(localStorage);
var list = "";
for (var i = 0 ; i < keys.length ; i++ ) {
list += keys[i] + "<br>";
}
$('#saved').append(list);

Object's push method not working properly [duplicate]

This question already has answers here:
Javascript Object push() function
(10 answers)
Closed 8 years ago.
I have a object for which i am using push method and it gives me length one more than expected.
var Object=[];
var temp = {};
var j=0;
while(j<2){
temp.id= j+1;
//other properties setting
Object.push(temp);
j++;
}
console.log(Object.length);
gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.
.push is a function of Array and not Object and don't use variable names that cause ambiguity.
Use:
var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
temp.id = j + 1;
//other properties setting
arr.push(temp);
j++;
}
console.log(arr.length);

Why this replace doesn't work Javascript? [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
I want to know why this procedure doesn't replace words
I have to do a procedure which reads a string and replace all word like this {{employee.Name}} into a value on the ticket's scope
var mySplitResult = Val.split(' ');
for (var i = 0; i < mySplitResult.length; i++) {
if (mySplitResult[i].match("{{") && mySplitResult[i].match(".")) {
var start = mySplitResult[i].lastIndexOf(".") + 1;
var end = mySplitResult[i].indexOf("}}");
var result = mySplitResult[i].substring(start, end);
for (var key in ticket.PNData) {
if (key == result) {
change.replace(mySplitResult[i], ticket.PNData[key]);
alert(change)
}
}
}
}
In JavaScript strings are immutable which means you must assign the result to a variable.
mySplitResult[i] = mychange.replace(mySplitResult[i], ticket.PNData[key]);

Categories