I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure).
I have the following problem. I build a dynamic searchstring.
Depends on the TLD a user decided to search for.
Here is my code:
if (tld == 0) {
var searchString = 'value.tld != ""';
}
if (tld == 1) {
var searchString = 'value.tld == "de"';
}
if (tld == 2) {
var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
}
if (tld == 3) {
var searchString = 'value.tld == "io"';
}
Depending on the search parameter 'searchstring', I build this routine with eval:
if (eval(searchString)) {
// Do something special, depends on the tld variable
}
How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.
Thanks in advance
Nick
How about:
let choices = {
1: ['de'],
2: ['com', 'net', 'org', 'info', 'biz'],
3: ['io']
};
function check(tldparam) {
if (tld === 0) {
return value.tld !== "";
} else {
return tld === tldparam && choices[tldparam].includes(value.tld);
}
}
And we test it like:
// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};
// This is my checking criterion
let tldparam = 2;
if (check(tldparam)) {
// Do something special, depends on the tld variable
}
Does it serve your purpose?
Related
How can I find out if a text input is a certain text?
I tried this
<script>
var b = document.getElementById('button')
var u = document.getElementById('username')
var p = document.getElementById('password')
var bannedUsers = ["user1012"];
b.onclick = function() {
if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
location.href = "";
};
if(u.value.length > 20) {
return alert('Username needs to be below 20 characters.')
} else if(u.value.length < 3) {
return alert('Username needs to be above 2 characters')
}
if(p.value.length < 6) {
return alert('Password needs to be over 6 characters.')
}
if(u.value === bannedUsers) {
return alert('That username is banned.')
}
}
</script>
But it ended up just taking me to the page instead of saying "This username is banned"
You need to use the includes method.
bannedUsers.includes(u.value)
what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'
You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (bannedUsers.includes(u.value) {
return alert('That username is banned.')
}
I'm writing code in vanilla JavaScript but I don't want to write a thousand different if statements.
I already tried searching up how to reduce if statements in JavaScript, but I didn't find anything helpful.
Here is some example code:
if (a == "text" && b == "othertext") {
console.log("message");
} else if (a == "text2" && b == "othertext2") {
console.log("other message");
} else if (a == "text3" && b == "othertext3") {
console.log("other other message");
} else if (a == "text4" && b == "othertext4") {
console.log("other other other message");
} else if (a == "text5" && b == "othertext5") {
console.log("other other other other message");
} else if (a == "text6" && b == "othertext6") {
// .. and so on.
}
If anyone can help me, it would be appreciated
You can use a data-driven approach by using the strings as keys in an object.
const messages = {
"text|othertext": "message",
"text1|othertext1": "message1",
"text2|othertext2": "message2"
};
function showMessage(a, b) {
let key = `${a}|${b}`;
if (messages.hasOwnProperty(key)) {
console.log(messages[key]);
} else {
console.log("Invalid a and b");
}
}
showMessage("text", "othertext");
You could use ternary operators I suppose.
let msg = '';
msg = a === 'text' && b === 'othertext' : msg;
msg = a === 'text2' && b === 'othertext2' : msg;
// etc.
Ultimately its not gonna get much prettier but that might be a little bit simpler to type.
I have strings that I have to insert in a db but I want to first modify their value if they fall under certain conditions.
For example I have the strings Epatite, Epatite B, EpatiteáB, EpB3 that I want them to be changed to EP B before being inserted into the db.
This is piece of my code:
// vaccines[index] is the string to compare
var vac = makeUniform(vaccines[index]);
const queryInsert = {
text: 'INSERT INTO coverages (vaccine) VALUES ($1) ON CONFLICT DO NOTHING;',
values: [vac]
}
var printText = '[INSERT Italy IN coverages]';
promises.push(postgreSQLlib.query(queryInsert, printText, false));
function makeUniform(val) {
if(val === 'DIF' || val === 'Difterite') {
return 'DIPH'; // diphtheria
}
else if(val === 'Epatite' || val === 'Epatite B' || val === 'EpatiteáB' || val === 'EpB3') {
return 'EP B'; // hepatitis B
}
else if(val === 'HIB' || val === 'Hib3' || val === 'Hib') {
return 'HIB'; // haemophilus influenzae B
}
else {
return val;
}
}
Whene I execute SELECT DISTINCT vaccine FROM coverages ORDER BY vaccine; on psql shell, I get:
DIPH
DT-DTP3
DTP3
EP A
EP B
EpatiteáB
Hib
HIB
M-MPR1
M-MPR1-MPRV ...
There is EpatiteáB which theoretically should have changed in EP B.
Why it doesn't work?
EDIT 1
vaccines[index] comes from an online pdf of which I did web scraping using the textract package of Node.js.
Thanks
Try to clean your development database first with this:
UPDATE coverages set vaccine = 'EP B' WHERE vaccine LIKE 'Epatite%' OR vaccine = 'EpB3';
Do something similar for the others.
Try this added one more condition = (val==="Epatite%E1B%21")
function makeUniform(val) {
if(val === 'DIF' || val === 'Difterite') {
return 'DIPH'; // diphtheria
}
else if(val === 'Epatite' || val === 'Epatite B' || val==="Epatite%E1B%21" || val === 'EpatiteáB' || val === 'EpB3') {
return 'EP B'; // hepatitis B
}
else if(val === 'HIB' || val === 'Hib3' || val === 'Hib') {
return 'HIB'; // haemophilus influenzae B
}
else {
return val;
}
}
I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.
This JavaScript function is in the webpage I am calling:
function getChecked(button, form) {
var name;
for (i = 0; i < document.forms['CheckForm'].list.length; i++) {
name = "Check" + (i+0);
if(document.forms['CheckForm'].list[i].checked == true) {
if(name == "Check0")
form.Check0.value = "2437315";
else if(name == "Check1")
form.Check1.value = "2437104";
else if(name == "Check2")
form.Check2.value = "2434936";
else if(name == "Check3")
form.Check3.value = "2434574";
else if(name == "Check4")
form.Check4.value = "2433541";
else if(name == "Check5")
form.Check5.value = "2426021";
}
Sometimes there are 6 checks, sometimes 7 sometimes 3, I need help in counting how many Check(Somenumber) there is and then build an post field with Check0=0&Check1=0&Check2=0 and so on.
I am not setting each check to different value, I need to count how many Checkboxes there are and then set them to 0, I am using PHP to cURL the page.
In javascript you can do something like this:
var form = top.document.forms.CheckForm;
var numFormElements = form.length;
var counter = 0;
for( i = 0; i < numFormElements && !foundItem; i++ )
{
var obj = form[i];
if( obj.type == 'checkbox' )
{
counter++;
}
}
alert( counter ); // or whatever else
I should add... I don't think that there's any way that a server-side language can know the type of input. That information has to be grabbed from the user's web browser through a client-side means.
You could just simply build the string as you go. There are other ways to do this (which I would suggest using jQuery with it and cycling through using "this"). Here is what I would do with your existing code.
//set a string
var values = '';
if(name == "Check0") {
form.Check0.value = "2437315";
values += 'Check0=' + form.Check0.value;
} else if(name == "Check1") {
form.Check0.value = "2437315";
values += 'Check1=' + form.Check1.value;
}