How to prevent multiple ", " from being appended in the string - javascript

I am trying to basically check if the string ends with ", " then do not append another ", " . If the string does not end with ", " then append ", ". I just want one ", " in between two strings. However as I hit the "compute" button of my script several times (which basically iterates the key values & appends the comma's between strings) , I get multiple ", " between two strings. What I tried does not really work.
eg:
Expected is abc, apple, pear, strawberry
even if I hit compute many times or one time
What I get after multiple clicks of compute button:
abc, , , , apple, , , , pear, , , , strawberry
Here's what I tried:
//Here obj[key][i] is the string
var lenson = obj[key][i].length;
if(1!=len-1){
if(obj[key][i].charAt(lenson-1) === " " && obj[key][i].charAt(lenson-2)=== ","){
}
else{
if(obj[key][i]!=""){
obj[key][i]+=", ";
}
}
li.appendChild(document.createTextNode( obj[key][i] ));
}

I am assuming you are getting your data from some sort of json object or similar. Since you are already looping over the keys, my advice would be to simple store them in an array. Then when you want to output them to string you just use .join(",")
var list = yourarray.join(",");

Related

Is the \n supposed to indent your text?

I'm a python programmer and in Python, the \n renders a new line like so:
print("Hello \n World")
Hello
World
But I'm trying to do that in Javascript with the following block of code:
if (userInput == wrongAnswer){
let finalScore = initialScore + scoreForA;
console.log(finalScore);
if (finalScore == 5){
console.log(rightScore);
}
else{
console.log("Initial score:", initialScore, "\n", outputA, "\n", "Final score:", finalScore);
}
}
Edit: By the way, I've defined these variables already.
But it gives me:
And I'm supposed to make it:
Is the \n supposed to auto-indent Wrong answer and Final score after making a new line in JavaScript?
Note that you're providing multiple arguments to console.log, so the python analog would be print("Hello\n", "World") which would add a space on the second line as well. Multiple arguments are always separated by a space, if you don't like that, concatenate them or use a template literal:
console.log(`Initial score: ${initialScore}\n${outputA}\nFinal score:${finalScore}`)
I think it is because the function console.log() adds a space between each params.
You can do that :
console.log("Initial score" + 5 +"\n" + "WrongAnswer" +" :(" + "\n" + "Final score -1");

Filter out words after divider in a string in Javascript

I have a variable which for example returns: +category1+author3
In my HTML I have 2 links: one with class="category1" and one with class="author3".
I want to hide both links (with for example $("a.category1").fadeOut(); ), but therefore I need to filter the words category1 and author3 out of the variable above. So I want to remove the divider + and let the code read that after every + comes a new word, which I want to use as a class in the further code.
So basically I want to get this +category1+author3 to two variables category1 and author3 with the + as divider using Javascript (there also can be 1 ore 3 or 4 words in the variable, like: +category1+category4+author3+genre2).
Use a string.split method on +
var s="+category1+author3";
classSplit=s.split("+"); //This will be an array
console.log(classSplit[1]) //category1
console.log(classSplit[2]) //author3
//console.log(classSplit[0]) This will be blank/null as there is nothing before+
EDIT:
for(i=1;i< classSplit.length;i++) {//Start with 1 as 0 is null
$classSplit[i].fadeOut();
}
try this
var classSelector = "+category1+author3".split("+").join(",.");
$( classSelector ).fadeOut();
or
var classSelector = "+category1+author3".replace(/\+/g, ", .");
$( classSelector ).fadeOut();

JS String concatenate encoding issue

I have two html datalists, and I get their input values to query a json file. I first search the keys of my json file which are college majors, their values are their courses. So once the object key equals the program, I return that element because I want to further query that element with the second input field which is a course number. This step is always successful at returning the correct program courses corresponding to the program input.
The second step is where things go bad. I want to now take that program element and look through all the names of the courses in that program. I concatenate the two input fields, program + " " + course. The program is a major like "CSE" or "I S" and the course is any 3 digit number like "143" or "310". Each object element in the program has a string name attribute like "CSE 143". This name attribute does not equal the program + " " + course even though they are both of type string and the same value WHEN I am looking at a program that has a space in it. For example, I want to find the course "I S 310". I successfully search for the program name that equals "I S". I iterate through the keys and find the correct element value using this operation Object.keys(jsondata[index]) == program. program is a variable containing the string "I S". As stated previously, this is successful, but if I iterate through the children of that objectkey value to find id, like programdata[index].children == program + " " + course, it doesnt work. If I instead hardcode the value, programdata[index].children == "I S 310", it works! This leads me to believe that the concatenation operation for these two variables changes the encoding of the string. According to console.log, the type of "I S 310" and program + " " + course are both Strings except they output a different encodeURIComponent().
Ill write what the output to the console is since im not reputable enough:
Step 1
function getProgramCourses(data, program) {
var programKeys = Object.keys(data);
for (var i = 0; i < programKeys.length; i++) {
if (Object.keys(data[i]) == program) {
return data[i][Object.keys(data[i])];
}
}
return objs
}
program = "CSE"
console.log(program)
console.log(encodeURIComponent(program));
Output:
CSE
CSE
program = "I S"
console.log(program)
console.log(encodeURIComponent(program));
Output:
I S
I%C2%A0S
Those unencoded hidden characters dont affect this first step of finding the courses offered by the "I S" program. Now when I want to find a specific course within the "I S" program like "I S 310":
Step 2
//data is object array of all courses in this program
function getCourse(data, program, course) {
pc = program + " " course;
for (var i = 0; i < data.length; i++) {
if (data[i].name == pc) {
return data[i];
}
}
}
"CSE" = program and "143" = course
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
CSE 142
CSE%20142
["I S" = program and "310" = course][2]
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
I S 310
I%C2%A0S%20310
This second step only works for programs that dont have spaces like "CSE" or "MATH". Doesnt work for "A A" or "I S". data[i].name is type String and so is pc.
Sorry about the lengthy post, I just wanted to be as descriptive as possible. Any help would be greatly appreciated.
Basically
Here is my problem:
console.log("A A 198")
console.log(encodeURIComponent("A A 198"))
console.log(program + " " + course)
console.log(encodeURIComponent(program + " " + course))
Output:
A A 198
A%20A%20198
A A 198
A%C2%A0A%20198
not equal
Your program variable contains a character which is like a space but isn't a space. Make sure it isn't an encoding issue, else you can fix this with this simple code.
encodeURIComponent(program.replace(/\u00a0/g, ' ') + ' ' + course)

WebSQL: Error processing SQL: number of '?'s in statement string does not match argument count

I want to create a dynamic function to INSERT data into the webSQL Database. I cannot use indexed DB because Zetakey does not support it.
tx.executeSql("INSERT INTO " + table + "(" + formatfields + ")
VALUES (" + formatqm + ")",
[formatvalues],
webdb.onSuccess,
webdb.onError);
Ich übergebe an den Query:
formatfields = "one, two"; (up to an undefined number)
formatqm = "?, ?";
formatvalues = "123, 456"; (dynamic user entries for x fields)
Can someone tell me what do I have to do with the formatvalues? When I write 123, 456 directly its working fine.
Thanks in advance!
Instead of dynamically create or change table column fields, use JSON serialization of the record. Basically store stringify user given object data on INSERT and parse on retrieval. If you need query over column, initialize those columns only. It will be just like IndexedDB does.
/*array.push */
formatvalues = new Array;
formatvalues.push("123");
and so on!

In Javascript, how do you access key value data from an object in a mixed array?

my name's Mike and my question is two-fold:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm trying to make a simple flashcard program to help me memorize different kinds of sound equipment. The list of equipment is large but I'm only including three different kinds to keep this example simple. I want each object to have two properties: answer and desc. This first part defines three objects, places them in an array, creates a variable for picking one of the array items randomely, and another variable for prompting the user for an answer:
var newFlash = function() {
var A827 = {
answer: "T",
desc: "Multitrack Tape Recorder"
};
var LA2A = {
answer: "O",
desc: "Classic Leveling Amplifier"
};
var SonyC800G = {
answer: "M",
desc: "Tube Condenser Microphone"
};
var list = [A827, LA2A, SonyC800G];
var rand = Math.floor(Math.random() * list.length);
var question = prompt("What kind of equipment is " + list[rand] + "?");
};
Now, if I make my three items in my array all strings, they show up no problem in the question prompt correctly replacing list[rand] with the appropriate array item. However, using objects in my array, my prompt says "What kind of equipment is [object Object]?.
My end goal is for the user to enter the appropriate one- or two-letter response (M for Microphone, C for Console, O for Outboard Gear, T for Tape Machine, S for Software, and CH for Computer Hardware) where upon entering the successful letter(s) yields an alert that displays both the object's answer and desc. My n00b instinct tells me this second part should be an if/else statement in the form of
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
}
else {
alert("Wrong, try again.");
}
but I'm very certain that this isn't the right way to access these object properties.
So, again, my question has two parts:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm sure some piece of logic is escaping me. Thanks for reading.
You want to use var question = prompt("What kind of equipment is " + list[rand].desc + "?");. list[rand] will yield you an object which has the structure {answer: "", desc: ""}, so you need to additionally access the description in your code.
Similarly, you want:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
}
else {
alert("Wrong, try again.");
}
To access the property of an Object in Javascript you use dot notation, as is common with many languages that have Objects. list is an array of Objects, so when you type list[rand] you are returning one of those Objects. Once you have an Object, you simply need to use the dot notation to access whatever property it is you require, in this case either desc or answer.
So instead of
var question = prompt("What kind of equipment is " + list[rand] + "?");
try
var question = prompt("What kind of equipment is " + list[rand].desc + "?");
Placing the property you are trying to access outside the bracket. This solves your second question as well, simply change:
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
to:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
this fiddle will help demonstrate.

Categories