My string reversing function appends “undefined” at the beginning - javascript

I have a short piece of HTML and JavaScript code. I wanted to write a function that reverses the input string. For example, input = hello, output = olleh.
This is what I have so far:
function go() {
var input = document.getElementById("input").innerHTML;
var output = document.getElementById("input");
var result = "";
for (var i = input.length; i >= 0; i--) {
result += input[i];
}
output.innerHTML = result;
}
onload = go;
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="question4.js"></script>
</head>
<body>
<div id="input">This text here</div>
<div id="output"></div>
</body>
</html>
Everything works fine, but the output has an undefined in front of the result. It looks like this:
undefinedereh txet sihT
How do I make the undefined go away?

Change: var i = input.length to var i = input.length-1 because the first time you loop you will be attempting to get input[i] (where i is the length of the input array).
If the array has 10 items in it, i will be 10, however the correct index for element 10 is 9.

start the loop from input.length-1

Related

put a save code in a text box and than change a variable to that save code

I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after

How to write the code in "function printOut(){} " in javascript?

I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>

How to break a word using Javascript

I'm developing a website and I need to break a word after "_".
For example, I have this "word":
test_test_test_test
And I want to break like this:
test_
test_
test_
test_
Is that possible?
Thanks.
I tried this, but didn't work:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var str = $('p').text();
var str_list = str.split("_");
for (var i = 0; i < str_list.length; i++) {
$('p').text(str_list[i] + "_");
}
});
</script>
</head>
<body>
<p>test_test_test_test</p>
<p>test2_test2_test2_test2</p>
</body>
</html>
'test_test_test_test'.match(/([a-z0-9]+_?)/gi)
the result is:
["test_", "test_", "test_", "test"]
You're looking for split.
var str = "test_test_test_test";
var str_list = str.split("_");
alert(str_list[0]);
If you want to print all of them then you need to iterate over the list.
for (var i = 0; i < str_list.length; i++) {
// I append the underscore to the end. Remove that bit if you don't want an underscore
alert(str_list[i] + "_");
}
var str ="test_test_test_test";
var parts=str.split('_');
parts.forEach(function(part){
alert(part+'_');
});
Here is another way to do it:
var words = word.replace(/_/g '_\0').split('\0');
The idea is to insert a marker after each _ and split on it. The marker should be a character that is not expected to appear in the actual data.

Trying to convert the values in a node to an array, clone a specific element and append the array items to that node with a class

<body>
<section id="que-container">
<div class="num" style="display: none">1000</div>
<section id="numberContainer">
<span class="number"></span>
</section>
<br class="clear">
</section>
<script src="components/jquery/jquery.min.js"></script>
<script src="components/bootstrap/js/bootstrap-button.js"></script>
<script src="components/bootstrap/js/bootstrap-carousel.js"></script>
<script src="js/scripts.js"></script>
<script>
$(document).ready(function(){
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 1; i < arr.length ; i++) {
$('#numberContainer').append(numbers.clone());
$('.number').append(arr[i]);
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
})
});
</script>
</body>
I am trying to get the values inside the '.num' div, convert it to an array and append the array's items to the '#numberContainer' within spans with the 'number' class. i am not getting any errors on the console but the code doesnt seem to work. any help? thanks
Your code has to be like this because arrays are 0 index based:
fiddle: http://jsfiddle.net/DZJ6p/
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 0; i < arr.length; i++) {
$('#numberContainer').append(numbers.clone().append(arr[i]));
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
});
you have a wrong selector here
$('.numbers').append(arr[i]); // i didn't find any element with numbers class
it should be
$('.number').append(arr[i]);
OR
numbers.append(arr[i]);
UPDATED
your for loop starts with var i as 1... so it is missing the first index of arr i.e. arr[0], I used this in youe code..
$('#numberContainer').append(numbers.clone().append(arr[i])); // u can use text(arr[i])) here
here is the fiddle...
http://jsfiddle.net/zLHxV/
i am not sure why you are using $('#numberContainer').append(numbers.clone());. Can you take a look at the js fiddle where i have put your code there.

How do I write a variable a certain amount of times?

var x=5
var char="Hi!
Is there any way to make JS write char x amount of times inside of an html element?
<span>Hyper guy wants to tell you
<script>
var x=5;
var char="Hi!;
document.write(char) and repeat x times;
</script>
</span>
The problem with using document.write is that it erases the whole page, so how would I insert it in context?
Use a loop that loops 5 times, each time adding 'Hi!' onto the end.
var x = 5;
var char = '';
while (x--) {
char += 'Hi!';
}
// write once
document.write(char);
Or, you can just write 5 times:
var x = 5;
var char = 'Hi!';
while (x--) {
document.write(char);
}
Up to you which you choose, though I'd prefer the first (the less you mess with the document, the better).
try this:
<span>Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var c="Hi!"; //close the quotes.
for (;x>=0;--x)
document.write(c);
</script>
</span>
document.write(..) doesnt erase the content of the entire page, if it is used in a proper way.
Really? I'm not sure where you got the idea that it erases the page first.
When I execute the following in FF3, after adding the missing closing quote following Hi!:
<html>
<head></head>
<body>
<span>
Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var chars="Hi! ";
var i;
for (i = 0; i < x; i++) document.write(chars);
</script>
</span>
</body>
</html>
I get:
Hyper guy wants to tell you Hi! Hi! Hi! Hi! Hi!
Create a HTML element in the page where you want to insert text
Use document.getElementById to get the element and append the text to element using .innerHTML .text property to it
http://www.tizag.com/javascriptT/javascript-innerHTML.php
example:
//add this empty span in the HTML page
<span id="newText"></span>
<script type="text/javascript">
var x=5, count;
var char='Hi!', resultString = '';
for(count=0;count<x;count++)
{
resultString = resultString + char;
}
document.getElementById('newText').innerHTML = resultString;
</script>

Categories