Is the \n supposed to indent your text? - javascript

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");

Related

Im doing a JavaScript CodeHS course, but what am I doing wrong?

Im doing intro to JS in a site called CodeHS. I believe I did the assignment its asking of me right but it says its wrong?
Here is what it wants me to do:
Here is what I did:
Heres what I apparently got wrong:
Ive run this code many times and it worked flawlessly, so why does it give me these errors?
You forgot to add a blank line inside the end of your while block, which also accounts for the line number. You should check the IMPORTANT note on the assignment.
I agree with #Jorge. You need to include the new line character '\n' at the end of the appropriate print statements, for the sake of the marking program. Try it like this:
while(numItems > 0) {
println('We have ' + numItems + ' in inventory.');
var buy = readInt('How many items would you like to buy?');
if(buy <= numItems) {
numItems -= buy;
println('Now we have ' + numItems + ' left.' + '\n');
} else {
println('There is not enough in inventory for that purchase.' + '\n');
}
}

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

LineBreak in console object

Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test

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)

To display long text area comments in a webpage

I have a long text area comment given as input by user. In order that it should be properly wrapped in my JSP, I'm using the below code. commentarea is my text area:
function addNewlines(commentarea) {
var result = '';
while ($.trim(commentarea).length > 0) {
result += $.trim(commentarea).replace(/[\s\n\r]+/g, ' ').substring(0, 40) + '\n'; commentarea= $.trim(commentarea).replace(/[\s\n\r]+/g, ' ').substring(40);
}
return result;
}
The text is getting wrapped but the problem is I'm getting white spaces between words that are at 40 character length. For example, in my output I'm getting a space between
prog rammable and sim ple
hello world today this is a simple prog rammable hello world today this is a sim ple prog rammable
orelse you better to use 'word-wrap' instead of that....refer this
This
You don't need any loops to replace all spaces and line breaks by a single space.
commentarea.value = commentarea.value.replace(/\s+/g, ' ').substring(0, 40);

Categories