Str.Slice Slicing Spaces - javascript

This is my typing game code. Feel free to test it if needed
<!DOCTYPE html>
<html onkeypress="myFunction(event)">
</head>
<body>
<style>
p::first-letter {
background-color: blue;
color: white;
}
</style>
<p id="demo"></p>
<script scr="script.js">
//base value for correct letters typed
var z = 0
//chooses random sentence (changable)
var myArray = [
"Repl.it is the best website in the world",
"Nothing can bet Repl.it in code editors",
"I hope the developers will give me hacker plan for complimenting Repl.it",
"Post your sentence suggestions below because I am horrible at creating sentences",
"I have been on Repl.it for 2 months",
];
var str = myArray[Math.floor(Math.random()*myArray.length)];
//replaces ('demo') with random sentence
document.getElementById("demo").innerHTML = str;
var a = str.length
var n = str.charAt(z)
console.log(a)
var x = null
var y = null
function myFunction(event) {
//find key pressed
x = event.keyCode;
y = String.fromCharCode(x);
myFunction2() //see below
}
function myFunction2() {
if (y == n) { //check if correct key
z = z + 1;
n = str.charAt(z)
console.log(n)
test()
document.getElementById("demo").style.color = "black";
} else { //if not correct key change to red
document.getElementById("demo").style.color = "red";
}
}
function test() {
if (z == a) {
document.write("END")
} else {
document.getElementById("demo").innerHTML = str.slice(z)
}
}
</script>
</body>
</html>
The str.slice is slicing off the spaces.
Is there any way to not slice the space?
or is there any other function which does it?
Which still leaves a space? (I couldn't find one online)
Thanks in advance,
Matthew

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

Array check with for loop

1.hey guys,how do i separate these?
2.sorry im newb in this,but been cracking my head for a while,how to make this code write sentences separetly without writing them non stop?
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++) {
var y=Number(prompt("enter number from 10 to 30",0));
for(i=0;i<=9;i++) {
if(y==x[i]) {//checking every number in array
document.write("u right.<br>");
e=e+1;
}
else {
document.write("u wrong.<br>");//this writes every time it goes trough the loop,i tried breaking,but it just quits the loop on first number in array,i tried continue,no luck
}
}
}
if(e<5) {//amount of time you guessed right
document.write("u lose ");
}
else {
document.write("u win");
}
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++)
{
var y=Number(prompt("enter number from 10 to 30",0));
var right = false;
for(i=0;i<=9;i++)
{
if(y==x[i]) //checking every number in array
{
right = true;
}
}
if (right)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{document.write("u win");}
</script>
</body>
</html>
Your code can be optimized in many areas:
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var c=0;
while (c < 10)
{
c++;
var y=Number(prompt("enter number from 10 to 30",0));
if (x.indexOf(y) != -1)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{
document.write("u win");
}
</script>
</body>
</html>
Use indexOf method of array for checking whether value is available in array or not.
If value is not available then return -1 else return position of that value.
<html>
<body>
<script type="text/javascript">
var x = [15,22,28,30,25,11,12,29,27,26];
var e = 0;
for (var c=1;c<=10;c++) {
var y = Number(prompt("enter number from 10 to 30",0));
x.indexOf(y) > 0?(document.write("u right.<br>"),e++):document.write("u r wrong.<br>");
}
e<5?document.write("u lose "):document.write("u win");
</script>
</body>
</html>

output as undefined/NAN

Would anyone clerify why my program is outputting undefined or NAN? I know for sure that my random number generator is working. Also, I'm trying to sum up all of the "score" value when the number generator has generated the value 10 times. Thanks for the help
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score;
var number;
number = randomnumber()
for (n=0;n<11; n=n+1)
{
if (number==0)
{
score =score+0
}
if (number==2)
{
score =score+2
}
if (number==3)
{
score =score+3
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
Because score variable is undefined. You should initialize it with a number for instance: var score = 0;
Variable score is declared in your totalscore function but never initialised. Adding anything to undefined gives NaN, which is what your function writes to the page.
You need to initialize your score variable with 0. Until you don't, it's value is undefined and when you do math operations on an undefined object, you wil get a NaN error. I have also formatted your code a bit.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
var number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0){
score += 0;
}
else if (number == 2)
{
score += 2;
}
else if (number == 3)
{
score += 3;
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
EDIT: If I understand your comment correctly, you should be doing something like this
function totalscore()
{
var n;
var score = 0;
for (n = 0 ; n < 10 ; ++n)
{
score += randomnumber();
document.write(score)
}
var grandTotal = score;
}

how to make a javascript input number positive and negative number

Hi, I am wondering how I would be able to do this code. I have an idea on how to make the javascript code, but I'm not sure if my code is correct. The question I have been given is:
Design and develop a javascript program that will determine if input
number is positive and negative.Consider zero(0) as
positive(considering that it contains no negative sign).
here is my javascript code, I'm not sure if this is correct based on the question above.
<!DOCTYPE html>
<html>
<head>
<title>activity 1</title>
</head>
<body>
<script type="text/javascript">
var stringNumber = prompt("Enter Number: ", "");
stringNumber = parseInt(stringNumber);
if(stringNumber >=80){
document.write("Positive");
}else{
document.write("Negative");
}
</script>
</body>
</html>
any answers are greatly appreciated.
Just check if the number is greater than or equal to 0
if(stringNumber >= 0)
{
document.write("Positive");
}
else
{
document.write("Negative");
}
var theNumber = prompt("Enter a Number:");
if (theNumber < 0) {
document.write("Negative");
}
else {
document.write("Positive");
}
Why you comparing number with 80? It should be 0
<script type="text/javascript">
var stringNumber = prompt("Enter Number: ", "");
stringNumber = parseInt(stringNumber);
if(stringNumber >=0){
document.write("Positive");
}else{
document.write("Negative");
}
</script>
And it work fine
Positive, negative & NaN:
var stringNumber = prompt("Enter Number: ");
stringNumber = parseInt(stringNumber, 10);
if (isNaN(stringNumber)) {
document.write("Not a Number");
} else if(stringNumber >=0) {
document.write("Positive");
} else {
document.write("Negative");
}

Create form for function Html

This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>

Categories

Resources