I'm writing a code that :
Allow my user to type in a sentence.
Find the longest word in that sentence.
Compare that longest one to every word in the sentence.
The words of the string directly out to a webpage, laid out so that no
single line is longer than the longest word in the string.
I've been working this code for two days and feel like completely lost in somewhere. Please advise me to improve my code.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to currend word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for ( i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthofString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var x = 0;
var testLength = 0;
var testLength = arrayOfText[i].length;
do {
testLength + 1 + arrayOfText[i].length
} while (testLength > longWord);
}
//Call this function in HTML
function wrapText(string) {
var length = longWord(string);
layoutString(string, length);
document.getElementById("demo").innerHTML += arrayOfText + "<br>";
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>
Some issues:
arrayOfText is not accessible in layoutString and wrapText as it is a locale variable of longWord
In layoutString you use longWord (the function name) instead of the parameter length.
The line "testLength + 1 + arrayOfText[i].length" has no effect, it just adds the three values together but does not assign it to anything.
layoutString generally does nothing ...
I'm not sure about your 4th requirement as all words' length will be less or equal than the longest word's length, so I add hyphens in front of all shorter words so they are all the same length. Maybe that gets you closer to your final goal.
Try this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to current word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthOfString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
while (arrayOfText[i].length < length) {
arrayOfText[i] = '-' + arrayOfText[i];
};
}
return arrayOfText;
}
//Call this function in HTML
function wrapText(string) {
var longestWordLength = longWord(string),
strings = layoutString(string, longestWordLength),
demo = document.getElementById("demo");
demo.innerHTML = '';
for (var i = 0; i < strings.length; i++){
demo.innerHTML += strings[i] + "<br>";
}
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>
Related
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
I have a typing field that's linked to the afinn word list. This is the project i am using: https://github.com/CodingTrain/website/tree/master/CodingChallenges/CC_044_afinn111SentimentAnalysis/P5
The detected words from the list are written below, telling the score of the word.
I want the detected words to be highlighted directly in the typing field. (shades of red for negativ words with a score from -5 to -1 and shades of green for positive words with a score from +1 to +5)
I was not able to create an example that runs in stackoverflow, but here's an example from github how it works right now:
https://darenr.github.io/afinn/
The piece of code will be used on a website.
The code is using the p5.js library and the afinn wordlist (json file): https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_044_afinn111SentimentAnalysis/P5/afinn111.json
I normally do design, so i'm really not good in coding. I hope you understand the question.
javascript:
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/VV1JmMYceJw
var afinn;
function preload() {
afinn = loadJSON('afinn111.json');
}
function setup() {
noCanvas();
console.log(afinn);
var txt = select('#txt');
txt.input(typing);
function typing() {
var textinput = txt.value();
var words = textinput.split(/\W/);
console.log(words);
var scoredwords = [];
var totalScore = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i].toLowerCase();
if (afinn.hasOwnProperty(word)) {
var score = afinn[word];
console.log(word, score);
totalScore += Number(score);
scoredwords.push(word + ': ' + score + ' ');
}
}
var scorePar = select('#scoreP');
scorePar.html('score: ' + totalScore);
var comp = select('#comparativeP');
comp.html('comparative: ' + totalScore / words.length);
var wordlist = select('#wordlistP');
wordlist.html(scoredwords);
//console.log(txt.value());
}
}
function draw() {
}
html:
<html>
<head>
<meta charset="UTF-8">
<title>AFINN-111 demo</title>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.dom.min.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"> </script>
</head>
<body>
<h1>AFINN Sentiment Demo</h1>
<p>
Type here:<br />
<textarea id="txt" cols=50 rows=10></textarea>
</p>
<p id="scoreP"></p>
<p id="comparativeP"></p>
<p id="wordlistP"></p>
</body>
</html>
Problem:
I need the scored words from the afinn list to be highlighted directly in the typing field. In shades of red (negative words, from -5 to -1) and shades of green (positve words, from +1 to +5)
I hope anyone can help! It would be so much appreciated!
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**
I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here
I have an array of strings,
["item1", "item2"]
I'd like to change my array to
["showItem1", "showItem2"]
The most easy to understand way of doing exactly what you ask for is probably something like this:
var items = ["item1", "item2"];
for (var i=0;i<items.length;i+=1) {
items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}
console.log(items); // prints ["showItem1", "showItem2"]
Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)
Strings are array-like. You could do this:
var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
var letters = arr[i].split('');
arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}
Demo: http://jsbin.com/asivec/1/edit
arr.map(function(i) {
return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
supported in Chrome, Firefox, IE9 and others.
Here is a reusable firstCharLowerToUpper() function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
span{
color:red;
}
</style>
</head>
<body>
<div>this is the text:
<span id="spn">
javascript can be very fun
</span>
</div>
<br/>
<input type="button" value="Click Here" onClick="change()"/>
<script>
function firstCharLowerToUpper(x)
{
var ar = x;
for (var i = 0; i < ar.length; i++)
{
ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
}
// join to string just to show the result
return ar.join('\n');
}
function change()
{
var ar = ["javascript ", "can ","be ","very ","fun" ];
var newtxt = firstCharLowerToUpper(ar);
document.getElementById("spn").innerHTML = newtxt;
}
</script>
</body>
</html>