Replacing Values in a String - javascript

Forgive me if this question has already been asked; I've searched the site for this question and haven't stumbled upon it yet.
I'm creating a word-guessing game, and I'm having trouble with the last of my functions. The function arguments are a user-inputted character ("character"), a randomly generated word ("word"), and a scrambled version of that word ("scrmbldword"). As an example, the word could be "chilly", and the scrambled version would have a corresponding number of underscores "______". The role of this function is to take the user input, scan the "word" for that letter, and if it finds that letter in the word, to replace an underscore of the "scrmbldword" with the corresponding letter.
For instance, the word would be "chilly", and the user input would be the character "l"; I need the scrmbldword to become "___ll_".
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
Thank you for all the answers, but when I copy and paste them into my code, they are not working. I'm trying to understand the code behind your various answers so I can edit them myself, but for the most part I don't get it. Perhaps it would help you all if I gave more context, so here's my file entirely...
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Word Guess Game</title>
</head>
<body>
<div>
<p id="directions-text">Type any letter to start playing</p>
<p id="userchoice-text"></p>
<p id="userguesslist-text"></p>
<p id="unscrambledword-text"></p>
</div>
<script type="text/javascript">
var userGuesses = [];
var unknownWord = "";
function wordGenerator() {
var computerChoices = ["lowly", "start", "chilly", "bun", "bead", "friend", "return", "view", "cloth", "frogs", "celery", "basin", "stand", "special", "broad", "abaft", "plead", "quartz", "mark", "tempt", "shop", "stone", "scorch", "taboo", "hoax", "spiffy", "insure"];
var cpuWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
console.log(cpuWord);
return cpuWord;
};
var computerWord = wordGenerator();
function scrambledWord(string) {
var knownWord = ""
if (string.length == 3) {
knownWord = "___"
} else if (string.length == 4) {
knownWord = "____"
} else if (string.length == 5) {
knownWord = "_____"
} else if (string.length == 6) {
knownWord = "______"
} else if (string.length == 7) {
knownWord = "_______"
}
return knownWord;
}
var unknownWord = scrambledWord(computerWord);
var directionsText = document.getElementById("directions-text");
var userChoiceText = document.getElementById("userchoice-text");
var userGuessList = document.getElementById("userguesslist-text");
var unscrambledWordText = document.getElementById("unscrambledword-text");
document.onkeyup = function (event) {
var userGuess = event.key;
if ((userGuess === "a") || (userGuess === "b") || (userGuess === "c") || (userGuess === "d") || (userGuess === "e") || (userGuess === "f") || (userGuess === "g") || (userGuess === "h") || (userGuess === "i") || (userGuess === "j") || (userGuess === "k") || (userGuess === "l") || (userGuess === "m") || (userGuess === "n") || (userGuess === "o") || (userGuess === "p") || (userGuess === "q") || (userGuess === "r") || (userGuess === "s") || (userGuess === "t") || (userGuess === "u") || (userGuess === "v") || (userGuess === "w") || (userGuess === "x") || (userGuess === "y") || (userGuess === "z")) {
userGuesses.push(userGuess);
directionsText.textContent = "";
userChoiceText.textContent = "You chose: " + userGuess;
userGuessList.textContent = "You have guessed: " + userGuesses;
unscrambledWordText.textContent = "The word is: " + unknownWord;
wordChecker(userGuess)
} else {
alert("You did not enter an alphabetical character.")
}
};
function wordChecker(input) {
if (computerWord.includes(input)) {
alert("You guessed a correct character")
unscrambledWord(input, unknownWord, computerWord)
} else {
alert("You guessed an incorrect character")
}
}
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}

As per my understanding, you can try this
function unscrambledWord(character, word, scrmbldword = "_".repeat(word.length)) {
return [...scrmbldword].map((d, i) => d == '_' && word[i] == character ? character : d).join('')
}
console.log(unscrambledWord('l', 'chilly'))

I think Nitish Narang is really a nice answer, but if you really want to use your existing function, you can try to define and use a replaceAt function, like this :
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replaceAt(k, character);
console.log(tempWord);
}
}
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
unscrambledWord("l", "______", "chilly")

You can use the replace method with a RegExp that has the global flag, which tells us to replace all instances of that RegExp.
RegExp(`[^${character}]`, "g")
We're making a regex that matches any character except the provided character.
function unscrambledWord(character, word) {
const notCharacter = RegExp(`[^${character}]`, "g")
return word.replace(notCharacter, "_")
}

Related

How to fix issue in my "isParenthesisValid" algorithm code

I am solving an algorithm question whereby it requires me to ensure that brackets, parenthesis and braces are put in the correct order or sequence.
Here is a link to the question, https://leetcode.com/problems/valid-parentheses/
An example is shown below:
Here is my code for the solution:
const isParenthesisValid = (params) => {
myList = []
lastElement = myList[myList.length - 1]
for (let i = 0; i < params.length; i++) {
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
// I get false as an answer everytime whether the pattern is correct or wrong
// false
console.log(isParenthesisValid("[()]"))
But I don't know why I get false everytime, I have compared my answer with someones else answer who did the same thing but it seems I am omitting something not so obvious.
I hope someone can point out in my code where i am getting it wrong.
Your lastElement retrieves the last element of the list at the start of the program - when there is no such element - so it's always undefined. You need to retrieve the value inside the loop instead.
const isParenthesisValid = (params) => {
myList = []
for (let i = 0; i < params.length; i++) {
const lastElement = myList[myList.length - 1]
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
console.log(isParenthesisValid("[()]"))
Or, a bit more readably:
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
const lastElement = openDelimiters[openDelimiters.length - 1];
if (delim === "(" || delim === "[" || delim === "{") {
openDelimiters.push(delim)
} else if ((delim === ")" && lastElement === "(") || (delim === "]" && lastElement === "[") || (delim === "}" && lastElement === "{")) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
Another approach, linking each delimiter with an object:
const delims = {
')': '(',
'}': '{',
']': '[',
};
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
if ('([{'.includes(delim)) {
openDelimiters.push(delim)
} else if (')]}'.includes(delim) && openDelimiters[openDelimiters.length - 1] === delims[delim]) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))

How to remove edge cases for string and number expressions

I'm building a rock, paper, scissors game and working on excluding edge cases.
The function is setPlayerMoves(), which is supposed to set previously undefined global variables for player moves and give them a 'value' between 1-99. how do I excluded edge cases like wrong move type (eg. 'rok') or wrong value (eg. 100).
Here is my incorrect code:
function setPlayerMoves(player, moveOneType, moveOneValue, moveTwoType, moveTwoValue, moveThreeType, moveThreeValue) {
if (player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99))) {
playerOneMoveOneType = 'rock';
playerOneMoveTwoType = 'paper';
playerOneMoveThreeType = 'scissors';
playerOneMoveOneValue = 11;
playerOneMoveTwoValue = 33;
playerOneMoveThreeValue = 55;
} else if (player === 'Player Two') {
playerTwoMoveOneType = 'rock';
playerTwoMoveTwoType = 'paper';
playerTwoMoveThreeType = 'scissors';
playerTwoMoveOneValue = 11;
playerTwoMoveTwoValue = 33;
playerTwoMoveThreeValue = 55;
}
}
Problem
Code for checking edge cases are wrong.
(player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99)))
Also you are checking the edge cases for only 'player one'
Solution
Check the values seperately before assigning values and create a valid variable
let valid = false
let states = ['rock','paper','scissors'];
if((states.indexOf(moveOneType) != -1) && (states.indexOf(moveTwoType) != -1) && (states.indexOf(moveThreeType) != -1)){
// valid state
valid = true;
}else{
valid = false;
}
if((moveOneValue >=1 && moveOneValue <= 99) && (moveTwoValue >=1 && moveTwoValue <= 99) && (moveThreeValue >=1 && moveThreeValue <= 99)){
//valid value
valid = true;
}else{
valid = false
}
Then assign the values.
if ((player === 'Player One') && valid) {
playerOneMoveOneType = moveOneType;
playerOneMoveTwoType = moveTwoType;
playerOneMoveThreeType = moveThreeType;
playerOneMoveOneValue = moveOneValue;
playerOneMoveTwoValue = moveTwoValue;
playerOneMoveThreeValue = moveThreeValue;
} else if ((player === 'Player Two') && valid) {
playerTwoMoveOneType = moveOneType;
playerTwoMoveTwoType = moveTwoType;
playerTwoMoveThreeType = moveThreeType;
playerTwoMoveOneValue = moveOneValue;
playerTwoMoveTwoValue = moveTwoValue;
playerTwoMoveThreeValue = moveThreeValue;
}
Also if possible
Create an object each for player1 and player2 like below and use.
let player1 = {
moveOneType:'rock'
moveTwoType:'paper'
moveThreeType:'scissors'
moveOneValue: 23
moveTwoValue: 33
moveThreeValue: 98
}

I'm having trouble programming my bulls and cows game in JavaScript

I'm a novice programmer and I've been using JavaScript to make a simple game of Bulls and Cows that updates with the amount of Bulls and Cows you have in a paragraph with each guess. I've been using "'1234'" in place of "arr.join("")" to test it out, and it's almost there, but it's adding one bull by default and not taking into account the first digit of the number being submitted. When I submit the correct number, everything comes up fine. I just wanted to know why I don't seem to be getting the proper amount of bulls and cows.
// This is our click counter that tells you how many times you've guessed in the game.
var clicks = 0;
$("#submit").click(function() {
clicks++;
$("#guesses").html(clicks);
});
// Generates a non-repeating, random number and stores it in a global variable known as "secret".
$("#start").click(function() {
var arr = [];
while (arr.length < 4) {
var randomnumber = Math.ceil(Math.random() * 9);
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === randomnumber) {
found = true;
break;
}
}
if (!found) arr[arr.length] = randomnumber;
}
secret = "1234";
});
// When you click the "Hide Rules" button, it hides the Rules form and shows the "Show Rules" button.
$("#hide").click(function() {
$("#rulesform").hide();
$("#show").show();
$("#hide").hide();
});
// When you click the "Show Rules" button, it shows the rules form and the "Hide Rules" button and hides the "Show Rules" button.
$("#show").click(function() {
$("#rulesform").show();
$("#show").hide();
$("#hide").show();
});
// When you click "Start playing!", it hides the button, shows the game, sets guesses equal to 0, and generates the number for the game.
$("#start").click(function() {
$("#game").show();
$("#start").hide();
$("#submit").show();
$("#guesses").html("0");
});
// When you hit the "Stop playing." button, it clears the results of the game and guess input box, in addition to hiding the game functions and showing the "Start playing!" button.
$("#stop").click(function() {
$("#game").hide();
$("#start").show();
$("#results").html("");
$("#guess").val("");
clicks = 0;
});
function game() {
// Stores your guess in a variable
var guess = $("#guess").val();
// Makes sure the number is 4 digits
if (guess.length != 4) {
alert("This number is too long or short to be valid.");
}
// Makes sure the numbers are non-repeating if they're 4 digits.
else if (guess.charAt(1) === guess.charAt(2) || guess.charAt(1) === guess.charAt(3) || guess.charAt(1) === guess.charAt(4) || guess.charAt(2) === guess.charAt(3) || guess.charAt(2) === guess.charAt(4) || guess.charAt(3) === guess.charAt(4)) {
alert("This game doesn't have any repeating digits.");
}
// This is the actual game.
else {
// These two variables will be updated with each guess the user inputs.
var bulls = 0;
var cows = 0;
// This is where JavaScript checks the bulls and cows and adds them up accordingly.
if (guess !== secret) {
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3) || guess.charAt(1) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3) || guess.charAt(2) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2) || guess.charAt(3) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(4) === secret.charAt(4)) {
bulls += 1;
} else if (guess.charAt(4) === secret.charAt(1) || guess.charAt(4) === secret.charAt(2) || guess.charAt(4) === secret.charAt(3)) {
cows += 1;
}
$("#results").html("Bulls: " + bulls + " & Cows: " + cows + "");
} else if (guess === secret) {
$("#results").html("<strong>Congrats, you won! <a href='images/cookie.gif'>Here's a picture</a> of a cookie.</strong>");
$("#submit").hide();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<h1>Want to play a game?</h1>
<div id="rules">
<form id="rulesform">
<h2>Rules:</h2>
<p>The computer will generate a random 4-digit number without any of them repeating. You will do your best to guess the number in the input field provided. If a digit you entered is not used, you will not get any bulls or cows. If it's in the correct
spot, then you'll get 1 bull. If it's in the wrong spot, it will be a cow. The game ends when you guess the number. The amount of guesses it takes for you to figure it out will be provided.</p>
</form>
<input type="button" id="hide" value="Hide Rules">
<input type="button" id="show" value="Show Rules">
<br>
<input type="button" id="start" value="Start playing!">
</div>
<!--closes rules-->
<div id="game">
<input type="number" id="guess" placeholder="Your Guess">
<input type="button" id="submit" value="Submit your guess." onclick="game()">
<br>
<p id="guesstext">Guesses:</p>
<p id="guesses"></p>
<p id="results"></p>
<input type="button" id="stop" value="Stop playing.">
</div>
<!--closes game-->
</div>
<!--closes wrapper-->
The first character in a string is charAt(0) in that string, not charAt(1). Reduce all your charAt references by one and see if that works.
Here's what it should look like:
// This is our click counter that tells you how many times you've guessed in the game.
var clicks = 0;
$("#submit").click(function() {
clicks++;
$("#guesses").html(clicks);
});
// Generates a non-repeating, random number and stores it in a global variable known as "secret".
$("#start").click(function() {
var arr = [];
while (arr.length < 4) {
var randomnumber = Math.ceil(Math.random() * 9);
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === randomnumber) {
found = true;
break;
}
}
if (!found) arr[arr.length] = randomnumber;
}
window.secret = "1234";
});
// When you click the "Hide Rules" button, it hides the Rules form and shows the "Show Rules" button.
$("#hide").click(function() {
$("#rulesform").hide();
$("#show").show();
$("#hide").hide();
});
// When you click the "Show Rules" button, it shows the rules form and the "Hide Rules" button and hides the "Show Rules" button.
$("#show").click(function() {
$("#rulesform").show();
$("#show").hide();
$("#hide").show();
});
// When you click "Start playing!", it hides the button, shows the game, sets guesses equal to 0, and generates the number for the game.
$("#start").click(function() {
$("#game").show();
$("#start").hide();
$("#submit").show();
$("#guesses").html("0");
});
// When you hit the "Stop playing." button, it clears the results of the game and guess input box, in addition to hiding the game functions and showing the "Start playing!" button.
$("#stop").click(function() {
$("#game").hide();
$("#start").show();
$("#results").html("");
$("#guess").val("");
clicks = 0;
});
window.game = function() {
// Stores your guess in a variable
var guess = $("#guess").val();
// Makes sure the number is 4 digits
if (guess.length != 4) {
alert("This number is too long or short to be valid.");
}
// Makes sure the numbers are non-repeating if they're 4 digits.
else if (guess.charAt(0) === guess.charAt(1) || guess.charAt(0) === guess.charAt(2) || guess.charAt(0) === guess.charAt(3) || guess.charAt(1) === guess.charAt(2) || guess.charAt(1) === guess.charAt(3) || guess.charAt(2) === guess.charAt(3)) {
alert("This game doesn't have any repeating digits.");
}
// This is the actual game.
else {
// These two variables will be updated with each guess the user inputs.
var bulls = 0;
var cows = 0;
// This is where JavaScript checks the bulls and cows and adds them up accordingly.
if (guess !== secret) {
if (guess.charAt(0) === secret.charAt(0)) {
bulls += 1;
} else if (guess.charAt(0) === secret.charAt(1) || guess.charAt(0) === secret.charAt(2) || guess.charAt(0) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(0) || guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(0) || guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(0) || guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2)) {
cows += 1;
}
$("#results").html("Bulls: " + bulls + " & Cows: " + cows + "");
} else if (guess === secret) {
$("#results").html("<strong>Congrats, you won! <a href='images/cookie.gif'>Here's a picture</a> of a cookie.</strong>");
$("#submit").hide();
}
}
}
I know it is not really on the topic, but I had to do the same task and found your code a really useful example. I kinda edited it and suggest you, something, that is far better option in my opinion(It is not necessary to be the better option, just my point of view)
for (var i = 0; i < length; i++) {
if(String(guess).charAt(i) == String(number).charAt(i)){
bulls++;
}else{
for (var j = 0; j < length; j++) {
if ((String(guess).charAt(i) == String(number).charAt(j)) && (i !== j)) {
cows++;
};
};
}
};
Where guess is your guess and number is the generated number.
The above code might be put instead of
if (guess.charAt(0) === secret.charAt(0)) {
bulls += 1;
} else if (guess.charAt(0) === secret.charAt(1) || guess.charAt(0) === secret.charAt(2) || guess.charAt(0) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(0) || guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(0) || guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(0) || guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2)) {
cows += 1;
}
I hope, I helped.

What is wrong with this code i have written? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to make all of the constants have next to them but nothing is working.
This is the javascript code here.
function opishConversion(text) {
var output = "";
for (var i = 0; i < text.length; i = i + 1) {
if ((text.charAt[i] !== "a") || (text.charAt[i] !== "A") || (text.charAt[i] !== "e") || (text.charAt[i] !== "E") || (text.charAt[i] !== "i") || (text.charAt[i] !== "I") || (text.charAt[i] !== "o") || (text.charAt[i] !== "O") || (text.charAt[i] !== "u") || (text.charAt[i] !== "U")) {
output += text.charAt[i] + "op";
} else {
output += text.charAt[i];
}
}
return output;
}
var text = prompt("Enter Text To Convert");
alert(opishConversion(text));
Any help would be appreciated.
charAt is a native method of the String primitive. It should be charAt(i) not charAt[i]
string.charAt is a function, not an indexed object. You need to use parantheses rather than square brackets.
so:
text.charAt(i);
rather than
text.charAt[i];
You also need to change your if statement to
&&
for AND instead of
||
corrected:
function opishConversion(text) {
var output = "";
for (var i = 0; i < text.length; i = i + 1) {
if ((text.charAt(i) !== "a") && (text.charAt(i) !== "A") && (text.charAt(i) !== "e") && (text.charAt(i) !== "E") && (text.charAt(i) !== "i") && (text.charAt(i) !== "I") && (text.charAt(i) !== "o") && (text.charAt(i) !== "O") && (text.charAt(i) !== "u") && (text.charAt(i) !== "U")) {
output += text.charAt(i) + "op";
} else {
output += text.charAt(i); //rather than text.charAt[i];
}
}
return output;
}
alert(opishConversion("aAbBcCdDeEfFgG"))
http://jsfiddle.net/8rrd9p9j/2/
chatAt() is a function so you should not be using square brackets
text.charAt(i);
All above answers will fix the issue that you have. However, I would also suggest you to simplify the logic by first changing the text to lowercase prior to the for loop.
http://jsfiddle.net/tr9qpqe8/
function opishConversion(text) {
var output = '';
var text = text.toLowerCase();
for (var i = 0; i < text.length; i++) {
if ((text.charAt(i) !== "a") || (text.charAt(i) !== "e") || (text.charAt(i) !== "i") || (text.charAt(i) !== "o") || (text.charAt(i) !== "u")) {
output += text.charAt(i) + "op";
} else {
output += text.charAt(i);
}
}
return output;
}
var text = prompt("Enter Text To Convert");
alert(opishConversion(text));

Cannot invoke function

See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);
You iterate on sString wich doesn't exist and not on your parameter aString.
Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.
Please change function myF(aString) to function myF(sString)
There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);

Categories