For loop in js with function for starter - javascript

I have a job. Unfortunately I got stuck. Could you help me.
Project:
Ask a sentence of user analysis.
Ask to see which letters you want the user to count the block.
Count the number of times that the letter occurs in the sentence.
A pop-up window and then type the following sentence: "The letter X times Y occurs in this sentence."
Must be use function!
I write this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
for (i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) {
alert("The letter " + letter + " occurs " + sentence.charAt(i) + " times in this sentence.")
}
}
return;
}
bernardTheLetterCounter();

You have to finish the counting (the inside of the loop) then print the result after the loop is done. Like this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
var count = 0; // the counter (initialized to 0)
// use var i instead of i (to make i local not global: this is just an advice)
for (var i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) { // if it is THE LETTER
count++; // increment the counter (add 1 to counter)
}
}
alert("The letter " + letter + " occurs " + count + " times in this sentence."); // use counter to print the result after the counting is done
// the return here has no meaning
}
bernardTheLetterCounter();
What you was doing is printing a message every time the letter is found (which is ugly for the user, especially if the count of that letter is big).

The function in this example can be re-used and tested. (ps. the for-loop is not a functional way of solving your problem).
var sentence = prompt("Please type in the phrase to be examined:");
var letter = prompt("Please enter the letter you are looking for:");
function countLettersInString(source, letterToFind) {
return source
.split('')
.filter(function(letter) { return letter === letterToFind; })
.length;
}
console.log([
'letter', letter,
'was found', countLettersInString(sentence, letter),
'times.'
].join(' '));

Related

How do I rewrite this as a function?

as part of a javascript course I've written a simple Caesar cypher script. I want to phrase it as a function but don't quite understand the syntax of functions.#
enter image description here
var userinput = prompt("What's your message?"); //get user input
let alphabet = "abcdefghijklmnopqrstuvwxyz"; //define alphabet
let alphabetupper = alphabet.toUpperCase(); //define alphabet uppercase (else it gets messy to do the lookup!)
let shift=15; //define letter shift
//___________________________________________
let result = "";
for (let i = 0; i < userinput.length; i++) {
let letter = userinput[i]; //declare letter as userinput char at index
if (letter.toLowerCase()==letter.toUpperCase()){ //if its not a letter...
result +=letter; //print it to result
}
else if ((letter===letter.toUpperCase())) { //else if it is an uppercase letter...
let j=alphabetupper.indexOf(letter); //get index of letter in alphabet "j"
if ((j+shift)<25){ //check shift pos is less than end of alphabet
result+= ((alphabetupper[j+shift])); //print uppercase letter 15 places forward of result
}
else if ((j+shift)>25){ //if the new index is past z...
result+=((alphabetupper[j+(shift-26)])); //loop past z
}
}
else if (/*(letter.toLowerCase()!==letter.toUpperCase())&&*/(letter==letter.toLowerCase())) { //if it is a lowercase letter...
let j=alphabet.indexOf(letter); //get index of letter in alphabet "j"
if ((j+shift)<25){ //check shift pos is less than end of alphabet
result+= (alphabet[j+shift]); //print letter 15 places forward to result
}
else if ((j+shift)>25){ //if the new index is past z...
result+=(alphabet[j+(shift-26)]); //loop past z
}
}
};
alert(("Your encoded message is ") + (result)); //Output result
All you have to do now is run the code i called the function in the last line
function ceasar (userinput){
var userinput = prompt("What's your message?"); //get user input
let alphabet = "abcdefghijklmnopqrstuvwxyz"; //define alphabet
let alphabetupper = alphabet.toUpperCase(); //define alphabet uppercase (else it gets messy to do the lookup!)
let shift=15; //define letter shift
//___________________________________________
let result = "";
for (let i = 0; i < userinput.length; i++) {
let letter = userinput[i]; //declare letter as userinput char at index
if (letter.toLowerCase()==letter.toUpperCase()){ //if its not a letter...
result +=letter; //print it to result
}
else if ((letter===letter.toUpperCase())) { //else if it is an uppercase letter...
let j=alphabetupper.indexOf(letter); //get index of letter in alphabet "j"
if ((j+shift)<25){ //check shift pos is less than end of alphabet
result+= ((alphabetupper[j+shift])); //print uppercase letter 15 places forward of result
}
else if ((j+shift)>25){ //if the new index is past z...
result+=((alphabetupper[j+(shift-26)])); //loop past z
}
}
else if (/*(letter.toLowerCase()!==letter.toUpperCase())&&*/(letter==letter.toLowerCase())) { //if it is a lowercase letter...
let j=alphabet.indexOf(letter); //get index of letter in alphabet "j"
if ((j+shift)<25){ //check shift pos is less than end of alphabet
result+= (alphabet[j+shift]); //print letter 15 places forward to result
}
else if ((j+shift)>25){ //if the new index is past z...
result+=(alphabet[j+(shift-26)]); //loop past z
}
}
};
alert(("Your encoded message is ") + (result)); //Output result
}
ceasar();
Put a function foo() { before your code and an } after it, and you've created a function with the name foo and no arguments.
When you now call the function by invoking it
foo();
you will execute the code between the curly braces {...}
Since ES6+ you can define the function as a const lambda (also code arrow function). like so:
const foo = () => { /* all your code */ }
You just have to define the function before using it, the approach above allows it to use the function before it appears in the source code.

To lower case using if else/ for

I am the very begginer (only if/else, for, while, slice etc) and i ve got a problem: so i wrote Hangman game. I need to put in there code saying ‘’let’s player upper case guess letter transform to lowercase one every time he puts uppercase letter”
Did i choose the right place for this new code in existing code?
Were my thoughts about appropriate code more or less right?
If not: what s wrong then?
var words = ["fish", "monkey", "pioni", "agreable"];
var randomWord = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
for (var i = 0; i < randomWord.length; i++) {
answerArray[i] = "_";
}
var ramainingLetters = randomWord.length;
//Game circle
while (ramainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter or press cancel to exit game");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Enter only one letter");
} else if (guess == guess.toUpperCase()) {
guess = guess.toLowerCase();
} else {
//renew game cycle
for (var j = 0; j < randomWord.length; j++) {
if (randomWord[j] === guess) {
answerArray[j] = guess;
ramainingLetters--;
}
}
}
// stop game
}
alert(answerArray.join(" "));
alert(" Cool! this word was " + randomWord);
You could easily solve your problem by converting the chosen word to uppercase and everytime the user puts in a letter, make that uppercase too.
var randomWord = words[Math.floor(Math.random() * words.length)].toUpperCase();
And convert your quess always to uppercase
guess = guess.toUpperCase();
This way everything is consistent.
If they type in a letter in lowercase its getting converted to uppercase and compared with the word also in uppercase.

How to set an alert if something is not in an array once

Hello I am trying to figure out how to set an alert("not a option") only once per onkeyup if the letter pressed is not in a a-z array.
When a correct onkeyup is pressed, then it runs through the array and removes it.
But I can't put it at the end of the function because it will pop up regardless...
And I can't put it in the loop because it will run multiple times.
//function that compares the letter inputted to the splitWord array
function checkLetter (letter) {
//setting to false first to cover any input
var letterGiven = false;
//run a loop and compare the letter and splitword
for (i = 0; i < numberEmptySpaces; i++) {
if (splitWord[i] === letter) {
letterGiven = true;
//if it is true then letter will equal emptydisplay and replace the "_"
emptyDisplay[i] = letter;
//this updates the emptyDisplay with the letter that was given.
$('#randomId').html(emptyDisplay.join(" "));
}
}
//if it is not true then you lose one live and the letter is unputted to userGuess array
if (!letterGiven) {
livesRemaining--;
userGuesses.push(letter);
$('#wrongWordId').html("[ " + userGuesses.join(", ") + " ]");
$('#livesId').html(livesRemaining);
}
console.log(userGuesses);
console.log(livesRemaining);
//checking to see if the empty display is undated when onkeyup is actived
console.log(emptyDisplay);
}
(This is for a hangman game, it works, just trying to spice it up)
//function that will only allow a-z and space bar to be pressed
function availableLetters(letter) {
var letterGiven = false;
var alphabet = 'abc defghijklmnopqrstuvwxyz'.split('');
//check to see if it splits when called, it does
for (i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter) {
letterGiven = true;
//removes the current letter from the alphabet array
alphabet.splice(i, 1);
}
}
}
//---------------------------------------------------------------
//starts the initial game
startUp();
//listens for an event, which is onkeyup
$(document).on("keyup", function(event) {
//creates a variable and converts into a string
//fromcharcode is a converts assigned number to a letter and event.which is the number
//toLowerCase just lower cases any string inputed
var keyLetter = String.fromCharCode(event.which).toLowerCase();
availableLetters(keyLetter);
checkLetter(keyLetter);
updateInfo();
You should use indexOf and according to that handle. And check the userGuesses array if don't want to show the alert again.
//function that compares the letter inputted to the splitWord array
function checkLetter (letter) {
//setting to false first to cover any input
var letterGiven = false;
//run a loop and compare the letter and splitword
if(splitWord.indexOf(letter)>=0){
letterGiven = true;
//if it is true then letter will equal emptydisplay and replace the "_"
emptyDisplay[i] = letter;
//this updates the emptyDisplay with the letter that was given.
$('#randomId').html(emptyDisplay.join(" "));
}
//if it is not true then you lose one live and the letter is unputted to userGuess array
if (!letterGiven && userGuesses.indexOf(letter)<0) {
livesRemaining--;
userGuesses.push(letter);
$('#wrongWordId').html("[ " + userGuesses.join(", ") + " ]");
$('#livesId').html(livesRemaining);
}
console.log(userGuesses);
console.log(livesRemaining);
//checking to see if the empty display is undated when onkeyup is actived
console.log(emptyDisplay);
}

javascript Letters only

I have created a quiz on javascript that once the user answers 4/6 or more correct they will then be asked for a First Name, Last Name and then be given a random 4 digit code. The part I'm having trouble with is making the FirstName and LastName letters only and also not allow and empty prompt.
Anyone know how i'd implement a Regex into this?
Anyone able to help?
function getAnswers(){
var amountCorrect = 0;
for(var i = 1; i <= 10; i++) {
var radios = document.getElementsByName('q'+i);
for(var j = 0; j < radios.length; j++){
var radio = radios[j];
if(radio.value == "1" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct number of answers: " + amountCorrect + " / 6");
if (amountCorrect <= 3){
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
else{
var firstname = prompt("Please enter your first name.");
var lastname = prompt("Please enter your last name.");
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function
close();
}
}
try this..
var alphaExp = /^[a-zA-Z]+ [a-zA-Z]+$/;
var firstname =prompt("Please enter your first name And Last Name","");
if (firstname ==null || firstname =="")
{
alert("First and last name must be filled out!");
location.reload(true);
}
else if (!firstname.matches(alphaExp))
{
alert("Name must contain letters only!")
location.reload(true);
}
else{ // your code here.
}
Try this regex:
^[A-Z][a-zA-Z]*$
This regex matches a string of letters:
Starting with the letter A-Z
Only allow letters from a-z and A-Z
It will not match an empty line or any other character.
/^[a-zA-Z]+$/
this will work for u.

Count how many times a single letter appears in a word

I am very new to JavaScript, and I'm trying to figure out how to count how many times a single letter appears in a word. For example, how many times does 'p' appear in 'apple'
Here is what I have written so far but am having trouble figuring out where am I going wrong.
var letterInWord = function (letter, word) {
var letter = 0;
var word = 0;
for (var i = 0; i < letter.charAt; i+= 1) {
if (letter.charAt(i) === " " = true) {
letter++;
console.log('The letter `letter` occurs in `word` 1 time.');
}
}
return letter;
};
You've got a number of problems:
You're reusing parameter names as local variable names. Use different identifiers to track each bit of information in your function.
letter.charAt is undefined, if letter is a number, and is a function if letter is a string. Either way, i < letter.charAt makes no sense.
If you're searching for letter in word why do you want to look at letter.charAt(i)? You probably want word.charAt(i).
" " = true makes no sense at all.
Perhaps you meant something like this?
var letterInWord = function (letter, word) {
var count = 0;
for (var i = 0; i < word.length; i++) {
if (word.charAt(i) === letter) {
count++;
}
}
return count;
};
'apple'.match(/p/g).length // outputs 2
in other words:
var letterInWord = function (letter, word) {
return (word.match( new RegExp(letter, 'g') ) || []).length;
};
FIDDLE
Here's a smaller function that also works with characters like $ or * (and since it's calling length on a string, there's no need to use || [])
'apple'.replace(/[^p]/g,'').length // outputs 2
function charcount(c, str) {
return str.replace(new RegExp('[^'+c+']','g'),'').length
}
console.log = function(x) { document.write(x + "<br />"); };
console.log( "'*' in '4*5*6' = " + charcount('*', '4*5*6') ) // outputs 2
console.log( "'p' in 'pineapples' = " + charcount('p', 'pineapples') )// outputs 3

Categories