Javascript change case for input value - javascript

Hi I'm learning Javascript so please excuse me for such a newbie question. I'm trying to remove space from the input value string after converted its Case. I thought it would work with the replace method, but I guess there is something missing.
HTML
<input type= "text" id="city2check">
<button type="submit" onClick="myCity()">Check</button>
JS
<script>
function myCity() {
var cleanestCities = ["Cheyenne", "Santa Fe", "Tucson", "Great Falls", "Honolulu"];
var check = city2check.value;
var firstChar = check.slice(0,1);
var otherChar = check.slice(1);
firstChar = firstChar.toUpperCase();
otherChar = otherChar.toLowerCase();
var checkcity = firstChar + otherChar;
checkcity.replace(/ /g, '');
var matchfound = false;
for (var i = 0; i < cleanestCities.length; i++) {
if (checkcity === cleanestCities[i]) {
matchfound = true;
alert("correct");
break;
}
}
if (matchfound === false) {
alert("sorry not correct");
//code
}
}
</script>
http://jsfiddle.net/LVXTB/1/

There are a number of logical errors, this is the working one
When comparing, I changed all city names to lowercase in your array and I got rid of the space for the array. If you just replace all the spaces in the input then it will never match the 2 word city since in your array there is a space. If you define your array without space, it would save the replace operation during the compare (see http://jsfiddle.net/LVXTB/9/).
Cleaned version http://jsfiddle.net/LVXTB/12/
function myCity() {
var cleanestCities = ["cheyenne", "santafe", "tucson", "greatfalls", "honolulu"];
var checkcity = city2check.value.toLowerCase().replace(/ /g, '');
var matchfound = false;
var l = cleanestCities.length;
for (var i = 0; i < l; i++) {
if (checkcity === cleanestCities[i]) {
matchfound = true;
alert("correct");
break;
}
}
if (matchfound === false) {
alert("sorry not correct");
//code
}
}
In your original code, you convert the first letter to caps and the rest to lowercase, so any 2 word city will not match since you have uppercase in the second word in your array.
When you replaced space with nothing, any 2 word city will not match since in your array you have a space.
Also checkcity.replace(/ /g, ''); does not assign the value of the result of the replace. The main issue is you converted all characters to lowercase but the first.
If the array has a mix case then you can do
if (checkcity === cleanestCities[i].toLowerCase().replace(/ /g, '')) {

Here's a better version of your function that deals properly with spaces and title case, especially for two-word cities.
function myCity() {
var cleanestCities = ["Cheyenne", "Santa Fe", "Tucson", "Great Falls", "Honolulu"];
var checkcity = city2check.value;
checkcity=checkcity.replace(/ +$/g, '');
checkcity=checkcity.replace(/^ +/g, '');
checkcity=checkcity.replace(/ +/g, ' ');
checkcity=checkcity.replace(/([^\W_]+[^\s-]*) */g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
var matchfound = false;
for (var i = 0; i < cleanestCities.length; i++) {
if (checkcity === cleanestCities[i]) {
matchfound = true;
alert("correct");
break;
}
}
if (matchfound === false) {
alert("sorry not correct");
//code
}
}
Using this code, type, for instance, " santa fe ", and it will clean it up appropriately.
http://jsfiddle.net/LVXTB/14/

Related

simple algorithm with indexOf not working in JS

my mission is to find and output, where the tabs/word entered, is placed in the sentence.
the console gives me back that place var is not defined. What should I do? Thank you very much!
var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);
if (stntence.indexOf(word) != -1) {
while (place != -1) {
if (place != -1) {
console.log("The place of the word/tab is: " + place);
counter = place++;
} else {
console.log("That's all")
}
}
} else {
console.log("the word/tabs are not exist in the sentence");
}
Beside the typo of stntence !== sentence, you could take the advantage of the counter and use a shortened approach by assigning the place directly in the while condition.
var sentence = prompt("Enter you sentence"),
word = prompt("Enter the tabs/word you looking for"),
counter = 0,
place = -1;
while ((place = sentence.indexOf(word, place + 1)) != -1) {
console.log("The place of the word/tab is: " + place);
counter++;
}
if (counter) {
console.log("That's all");
} else {
console.log("the word/tabs are not exist in the sentence");
}

Compare two string in js and find difference

how to compare two strings purely, and provide specific result such as highlight extra word, wrong word & skip word in 2nd string. for eg.
var x = "This is the first original string in javascript language." </br>
var y = "This is not the first org string in language."
diff = wrong word ="org"<br>
Extra word ="not"<br>
skip word ="javascript"
//here is slice of my code but in some case my program fails
var x = "here is some value of string";
var y = "here is the some val string";
var k=0;
var SkipWrd="";
for(var i=0; i<y.length;i++){
var sktmp="";
var swtmp=0;
for(var j=0; j<=2;j++) {
if(x[k]!="undefined"){
if(y[i]==x[k+j]){
SkipWrd+=sktmp;
skip+=swtmp;
H_wrd += typ_wrd[i]+" ";
org_para+= sktmp+x[k+j]+" ";
k+=j+1;
break;
}
else{
sktmp+= "<mark>"+ x[k+j]+" "+ "</mark>";
swtmp++;
if(j==2 && y[i]!=x[k+j]){
err++;
Err_Wrd+=y[i]+" ";
H_wrd += "<span id='H-Err'>" + typ_wrd[i] + "</span> ";
org_para+="<span id='O-Err'>" +x[k]+" "+ "</span> ";
k++;
}
}
}
}
}
I have used a word by word comparison approach rather than the character by character approach you used. The overall logic is similar.
The below code will work for your example, but there are many more cases that might go wrong.
var x = "This is the first original string in javascript language.";
var y = "This is not the first org string in language.";
x=x.split(' ');
y=y.split(' ');
var i=0,j=0;
while (1) {
if (!x[i] || !y[j]) break;
if (x[i] == y[j]) {
i++;
j++;
continue;
}
if (x[i] == y[j+1]) {
console.log('Extra word : ', y[j]);
i++;
j+=2;
continue;
}
if (x[i+1] == y[j]) {
console.log('Skip word: ', x[i]);
i+=2;
j++;
continue;
}
if (x[i+1] == y[j+1]) {
console.log('Wrong word: ', y[j]);
i++;
j++;
continue;
}
}

How to return array item after converted by pressing a key

I'm building a game and I've done this:
var names=["Adam Black", "Brad White"];
var namePicked = var namePicked = names[Math.floor(Math.random() * names.length)]; //pick a random name
var nameArray = namePicked.split(""); //turn name string into array of letters
var nameHidden = [];
window.onload = function() {
//replace each of the letters with underscore and space with dash
for (var i = 0; i < nameArray.length; i++) {
if (nameArray[i] == " ") {
nameHidden += "- ";
}
else {
nameHidden += "_ ";
}
}
document.getElementById("nameDisplay").innerHTML = nameHidden;
}
//get key pressed by user
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
nameArray = nameArray.map(function(x) {return x.toLowerCase()}); //lowercase all letters so uppercase letters get caught when key pressed
// check letter entered with letters of names
for (var i = 0; i < nameArray.length; i++) {
if (charStr == nameArray[i]) {
}
}
}
And I'm stuck here. How to switch/replace the values back to letters?
for example: "Adam Black" will be converted to 4 underscores 1 dash and 5 underscores, and when the user presses key a, both letter a will show up:
A _ a _ - _ _ _ _
I can't change the nameHidden[i] back to nameArray[i] when the right key is pressed. I can get the value of the key pressed with console.log.
I've tried loops, new var, boolean...
Also, how can I make sure when a key is presesd (ie "a"), the user can press it again but nothing happens?
You're not that far off, but it would be easier to make the part that updates the HTML into a function, and just call that function with the given character, something like
var names = ["Adam Black", "Brad White"];
var namePicked = names[Math.floor(Math.random() * names.length)]; //pick a random name
var nameArray = namePicked.split(""); //turn name string into array of letters
var updated = []; // keep track of values that are already updated
function display(char) {
//replace each of the letters with underscore and space with dash
char = char || '_'; // set to default when no char given
var nameHidden = [];
for (var i = 0; i < nameArray.length; i++) {
if (updated[i] || (char.toLowerCase() === nameArray[i].toLowerCase())) {
nameHidden += nameArray[i];
updated[i] = true;
} else if (nameArray[i] == " ") {
nameHidden += "- ";
} else {
nameHidden += "_ ";
}
}
document.getElementById("nameDisplay").innerHTML = nameHidden;
}
//get key pressed by user
document.addEventListener('keypress', function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
display(charStr); // call when typing
});
display(); // call onload
<div id="nameDisplay"></div>
<br /><br /><br />
<p>Focus here, and hit keys !</p>
Another approach is to define a function that converts a regular name into a hidden name (with the underscores and dashes), knowing the characters that have been pressed in an array.
function convertToHidden(name, charsPressed) {
var hiddenName = "";
// iterate over each character in the |name| string
for (var n=0; n<name.length; n++) {
var currCharInName = name[n];
// now check if that character has been pressed
var hasBeenPressed = false;
for (var p=0; p<charsPressed.length; p++) {
if (charsPressed[p] == currCharInName) hasBeenPressed = true;
}
if (hasBeenPressed) hiddenName += currCharInName;
else hiddenName += "_";
hiddenName += " ";
}
return hiddenName;
}
Then you could use this in the keypress function like so:
var charsPressed = [];
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
if (! charsPressed.includes(charStr)) charsPressed.push(charStr);
var nameHidden = convertToHidden(namePicked, charsPressed);
// display |nameHidden|
}

How to make sure user input is a valid string in js

I am very new to JS,
how do I make sure that the user input is a valid string?
If the string is inside of the array, the game should continue.
if the string is outside of the array, the game should ask user to input their guess again.
var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;
function do_game() {
var random_number = Math.random()* color.length;
var random_number_interger = Math.floor(random_number);
target = random_number_interger + 1;
rightAnswer = color[target];
while(!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
guess_input = guess_input_text;
guesses +=1;
finished = check_guess();
}
}
function check_guess() {
if(guess_input < rightAnswer){
console.log("Hint: your color is alphabetically lower than mine")
return false;
}
else if( guess_input > rightAnswer) {
console.log("Hint: your color is alphabetically higher than mine ")
return false;
}
else (guess_input == rightAnswer)
{
console.log("Congrats!!!")
return true;
}
)
}
You can use indexOf to check the position of guess_input in the color array. It will return -1 if it is not present.
So:
function check_guess() {
if (color.indexOf(guess_input) < 0) {
console.log("Not a valid colour, try again.");
return false;
}
return true;
}
You can use Array.prototype.find function with ES6 arrow functions to make it even snappier.
if(color.findIndex(e => e === guess_input) === -1){
alert("Please guess again!);
}
The above code alerts the user to guess again if the guess_input isn't found in the array.

How to remove space from RiTa.js random word generator?

I'm working on a word generator inspired by Daniel Shiffman's demo of the RiTa library. Right now, the code adds a space between all words and punctuation using the line:
output += " ";
I have been trying to figure out how to change the code so that space does not appear between punctuation (such as periods) and words. I think the simplest way to do this would be to use an if/else statement that leaves punctuation unaltered but adds space to words, but I am having a hard time figuring out what functions from the Rita library to use for this, as well as the syntax.
Any ideas? Here's my code right now:
var input;
var button;
var lexicon;
function setup() {
noCanvas();
lexicon = new RiLexicon();
input = createInput('As I say a noun is the name of a thing.');
button = createButton('submit');
input.changed(processRita);
button.mousePressed(processRita);
input.size(400);
}
function processRita() {
var s = input.value();
var rs = new RiString(s);
var words = rs.words();
var pos = rs.pos();
console.log(words);
console.log(pos);
var output = '';
for (var i = 0; i < words.length; i++) {
if (/nn.*/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
if(alliterations.length == 0){
output+=words[i];
}else{
output += alliterations[Math.floor(Math.random() * alliterations.length)];
}
//console.log("noun");
//console.log(alliterations.length);
} else if (/jj.*/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
output += alliterations[Math.floor(Math.random() * alliterations.length)];
//console.log("adjective");
} else if (/vb/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
output += alliterations[Math.floor(Math.random() * alliterations.length)];
//console.log("verbs");
}
else {
//console.log(words[i]);
output += words[i];
} {
output += " ";
}
}
createP(output);
}
Why do you need a library for this? Can't you just use the regular String functions to test whether a String is a punctuation mark?
You could just use a regular expression to test whether a String matches a punctuation character. Or just use a series of equality checks against each punctuation mark you care about.
You might also check out the startsWith() function and the endsWith() function.
after much trial and error, I had help from a coding professor who helped me to solve this problem, which was more complicated than I originally anticipated. In order to get this code to work, we added this bit toward the beginning of the for loop:
if(words[i] == "." || words[i] == "," || words[i] == "?" || words[i] == "!"){
output += words[i];
}else{
output += " ";
So the entire code now looks like this:
for (var i = 0; i < words.length; i++) {
if(words[i] == "." || words[i] == "," || words[i] == "?" || words[i] == "!"){
output += words[i];
}else{
output += " ";
if (/nn.*/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
if(alliterations.length == 0){
output+=words[i];
}else{
output += alliterations[Math.floor(Math.random() * alliterations.length)];
}
//console.log("noun");
//console.log(alliterations.length);
} else if (/jj.*/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
output += alliterations[Math.floor(Math.random() * alliterations.length)];
//console.log("adjective");
} else if (/vb/.test(pos[i])) {
var alliterations = lexicon.alliterations(words[i]);
output += alliterations[Math.floor(Math.random() * alliterations.length)];
//console.log("verbs");
}
else {
//console.log(words[i]);
output += words[i];
}
}
}
createP(output);
}
Its much simpler if you use the RiTa library functions:
function processRita() {
var all, output = [],
words = RiTa.tokenize(input.value()),
pos = RiTa.getPosTags(words);
for (var i = 0; i < words.length; i++) {
if (/[nn|kk|vb|jj].*/.test(pos[i]) && (all = lexicon.alliterations(words[i])).length) {
output.push(RiTa.randomItem(all));
} else {
output.push(words[i]);
}
}
createP(RiTa.untokenize(output));
}

Categories

Resources