insert into item.innerHTML - javascript

I've got a div remaining
remaining.innerHTML = "You have NUMBER remaining SECOND VARIABLE"
I know I can change innerHTML by just doing remaining.innerHTML = "new string" but I'm wondering using Javascript how would I inject a new value for NUMBER into the innerHTML without knowing NUMBER's index or value? However the non-variable contents e.g You have and remaining are constant.

Using string concatenation:
var number = 1;
var secondVariable = 2;
remaining.innerHTML = "You have " + number + " remaining " + secondVariable;
// results in "You have 1 remaining 2";

You can use the replace() method on the string, to replace your markers by their values.
For example, if you use this portion of code :
var str = "You have NUMBER remaining SECOND VARIABLE";
var new_str = str.replace('NUMBER', 150).replace('SECOND VARIABLE', 'plop');
The new_str variable will have as value :
"You have 150 remaining plop"
Which, applied to your specific case, would give something such as this :
remaining.innerHTML = "You have NUMBER remaining SECOND VARIABLE".replace('NUMBER', 150).replace('SECOND VARIABLE', 'plop');

remaining.innerHTML = "You have " + var1 + " remaining " + var2;

Something like
var no1 = 5;
var no2 = 10;
remaining.innerHTML = "You have " + no1 + " remaining " + no2;

Related

javascript count black spaces as 0?

I am building a script that is embedded in HTML to generate a report that extracts information from an internal company system.
The objective is to build some kind of a funnel, making the sum of records in each of the stages. For example, I have:
Processes in stage 1 = "3"
Processes in stage 2 = "5"
Processes in stage 3 = " "
Processes at stage 4 = "2"
Processes in stage 5 = " "
However, I have a problem when one of the stages is empty (it is not 0) because there is no stage in that specific process. When I try to add, for example, Stage 1 and Stage 3, it always returns an empty value, while it should give result 3 (3 + 0).
<p id="global_calc"></p>
<script>
{
var A = Stage1.system.count;
var B = Stage2.system.count;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
</script>
The Stage.system.count is the internal system's variable that has the number I want to eventually sum with var total.
But, for example, if Stage1.system.count = 3 and Stage2.system.count = " ", total result in " " instead of 3. How can I make this to count the black space as a 0?
First it's probably worth checking what variables you have; any number + " " will always give you a string:
const x = 123 + " "; // "123 ";
const y = 123 + "" // "123"
We can see that in practice in your example:
{
var A = 3;
var B = " ";
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
console.log(("The total of this stage is: " + total).replace(/ /g, '*'))
<div id="global_calc"></div>
It seems like you're using undefined as part of the addition, which returns the value NaN:
{
var A = 3;
var B = undefined;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
console.log(("The total of this stage is: " + total).replace(/ /g, '*'))
<div id="global_calc"></div>
We'll need more details to figure out exactly why you're getting " " for total.
If you want a function which converts number -> number and " " -> 0 then Number would do:
const x = 3;
const y = " ";
console.log(Number(x));
console.log(Number(y));

How to find hyphenated Strings

I search for specific words in a text and find them too. However, if the word I am looking for is divided into two lines by a hyphenation, the word will not be found. Here is a sample code.
searchString = "Hollywood";
newString = "";
text = "In India Hollywood is called Bollywood.";
var i = 0;
i = text.indexOf(searchString, i);
newString += text.substring(0, i) + " <<here begins my searchString>> " + text.substr(i, searchString.length) + " <<here ends my searchString>> " +
text.substring(i + searchString.length);
console.log(newString);
If the searchString Hollywood looks like
Holly-<br>wood
it will not be found.
How can I solve this problem in my Javascript code?
There are a few ways you could do it, but one of them would be to get rid of the - altogether if they're present:
searchString = "Hollywood";
newString = "";
text = "In India Holly-<br>wood is called Bollywood.";
filteredText = text.replace(/-<br>/,'');
var i = 0;
i = filteredText.indexOf(searchString, i);
newString += filteredText.substring(0, i) + " <<here begins my searchString>> " + filteredText.substr(i, searchString.length) + " <<here ends my searchString>> " +
filteredText.substring(i + searchString.length);
console.log(newString);
In this case, we just replace the -<br> characters with an empty string. It might not be the best approach, but refining it would depend on the context in which you intend to use it.
I hope that the regex and replace idea can help you customize a solution that best fit your needs.

javascript lotto task for loop+match

I´m stuck in this task, is a lotto generation, and I have to use a for loop, a match and AND, but I don´t know where use the AND compound, and the code that I have wrote is not working, any help?
Use a For loop to step through each position in the winning numbers array and
to compare the customer number to each number the array contains.
To complete this, you will need to set up the following.
1. A counter variable (e.g. i) for the loop.
2. A boolean variable (e.g. match) to flag if a match has been found or not.
3. A compound AND condition that allows the loop to continue to iterate only
if a match is not found, and, the end of the array has not been reached.
4. An if statement nested inside the For loop which checks the customer
number against each winning number in the array, each time the loop
iterates, and sets the boolean, match, to true if a match is found.
This is my code
var customerNumbers = prompt ("Please enter your number");
var winningNumbers = ['12','17','24','37','38','43'];
var match = false;
//These are the messages that will be show
var winningMessage = "This Week's Winning Numbers are:\n" + winningNumbers + "\n";
var customerMessage = "The Customer's Number is:\n" + customerNumbers + "\n";
var winnerMessage = "We have a match and a winner";
var notWinnerMessage = "Sorry you are not a winner this week";
/* Adding a for loop with a conditional and a boolean
*/
for (i=0; i<winningNumbers.length; i++) {
if (!match){
alert( winningMessage + customerMessage + notWinnerMessage);
}
else {
alert( winningMessage + customerMessage + winnerMessage);
}
}
Many thanks
Try this (if customerNumbers are comma separated):
var customerNumbers = prompt("Please enter your number").split(/\s*,\s*/);
var winningNumbers = ['12','17','24','37','38','43'];
var match = true;
//These are the messages that will be show
var winningMessage = "This Week's Winning Numbers are:\n" + winningNumbers + "\n";
var customerMessage = "The Customer's Number is:\n" + customerNumbers + "\n";
var winnerMessage = "We have a match and a winner";
var notWinnerMessage = "Sorry you are not a winner this week";
/* Adding a for loop with a conditional and a boolean
*/
for (i=0; i<winningNumbers.length; i++) {
if (customerNumbers.indexOf(winningNumbers[i]) === -1) {
match = false;
break;
}
}
if (!match){
alert( winningMessage + customerMessage + notWinnerMessage);
} else {
alert( winningMessage + customerMessage + winnerMessage);
}

issue with adding values from array

I am writing a small application for the user to enter the name of a book and then its price, push the values of those to an array, output the book name and cost to the page and then display the total.
the issue I am having is with the total, for example:
If I write 2 as the value of each of the values, the "totalOutput" says 022222 instead of 10 as I would expect, I have tried a few different things and read a few articles on here but haven't found any to be much help or that useful.
these are the exact lines I am having issues with:
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
And incase you need it - here is my full javascript code:
//Book shop task
function trackBooks() {
//target the output ul and store in a variable
var output = document.getElementById("booksOutput");
//Setup the two arrays to hold the book names and their prices.
var books = [];
var price = [];
//declare a variable for working out the total
var total = 0;
//target the total output
var totalOutput = document.getElementById("totalOutput");
//set up a counter for the loop
var x = 0;
//setup the loop for entering the names of the books and their prices, for the sample, I have set the loop to run 5 times as stated in the pseudo code
for (var i = 0; i < 5; i++) {
//add one to the counter on each loop
x = x + 1;
//declare a variable to ask the user for the book name and the cost and push those values to their arrays we created above
var bookName = prompt("enter book name number " + x);
books.push(bookName);
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
//create a variable to create new li tags on output
var newLi = document.createElement("li");
//add the required info to the new link
newLi.innerHTML = "book " + x + ": " + "<strong>" + books[i] + "</strong>" + " costs " + "<strong>" + price[i] + "</strong>";
//write out the name and price to the page
output.appendChild(newLi);
}
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
prompt returns a string, and when you add a number (0) and a string ("2"), you get a string ("02"). You should cast to number here:
price.push(+bookPrice);
(unary + casts to a number)
You are adding Strings not a Numbers. For example:
"Hello " + "World";
Will output "Hello World".
"10" + "20";
will output "1020"
Instead you have to convert the String to a Number
Number("10") + Number("20");
will ouput 30
To apply this to your code:
price.push(Number(bookPrice));

how can i add a value from an array to a value from an another one in javascript?

So, I have two arrays: grade[] and grade2[] that contains elements I give from windows.prompt . I want to add a value from grade with a value from grade2 so i can calculate "media". But the code that i wrote just concats those two values, doesn't add them actually. I am a beginner and I hope you can help me. Thank you!
function display_student()
{
var n=window.prompt("Number of students: "+"");
var name= new Array(n);
var grade=new Array(n);
var grade2=new Array(n);
var y=0;
for (y=0; y<n; y++)
{
name[y]=window.prompt("Student name:","");
grade[y]=window.prompt("Grade 1: ","5");
grade2[y]=window.prompt("Grade 2: ","5")
document.write("</br>"+"Student name: "+name[y]+"</br>"+"Grade 1: "+grade[y]+" </br>"+"Grade 2: "+grade2[y]+"</br>");
var media=(grade[y]+grade2[y])/2;
document.write("Media: "+media+"</br>");
if(media<5)
document.write("Failed");
else
document.write("Promoted");
}
}
Use the parseInt function before adding.
var media=(parseInt(grade[y]) + parseInt(grade2[y]))/2;
Because they are strings and no numbers.
Take a look at parseInt(string, radix)
http://jibbering.com/faq/notes/type-conversion/
Use:
var media=(parseInt(grade[y], 10)+parseInt(grade2[y], 10))/2;
Assuming your grades are integers. Otherwise, use parseFloat (in that case, you won't need the second parameter).
Use parseFloat:
var media=(parseFloat(grade[y])+parseFloat(grade2[y]))/2;
The values in the array are of type String (as returned by the window.prompt function) you need to convert them to numbers to add them together :
function display_student() {
var n = window.prompt("Number of students: " + "");
var name = new Array(n);
var grade = new Array(n);
var grade2 = new Array(n);
var y = 0;
for (y = 0; y < n; y++) {
name[y] = window.prompt("Student name:", "");
grade[y] = window.prompt("Grade 1: ", "5");
grade2[y] = window.prompt("Grade 2: ", "5"); // added semi-colon here too
document.write("</br>" + "Student name: " + name[y] + "</br>" + "Grade 1: " + grade[y] + " </br>" + "Grade 2: " + grade2[y] + "</br>");
var media = (parseFloat(grade[y]) + parseFloat(grade2[y])) / 2;
document.write("Media: " + media + "</br>");
if (media < 5) {
document.write("Failed");
} else {
document.write("Promoted");
}
}
}
Working example : http://jsfiddle.net/z5cUw/
This is an indirect answer because this is tagged homework.
Because window.prompt returns a string by default, you need to convert this string to a number. There are several methods to do this.
You can use parseInt() as several people have suggested. Returns an integer value.
You can use parseFloat() as suggested.
You can force it using a simple number division on the prompt: window.prompt("Grade 1: ","5")/1; or during the media calculation: var media = (grade[y]/1 + grade2[y]/1) / 2;
You can use the Number() function: Number(window.prompt("Grade 1: ", "5"));
It is up to you to determine which is the appropriate method for your needs. What if the value entered is NOT a number? Study each of these methods to determine which best suites your needs.

Categories

Resources