Making secret language useing charAt - javascript

I need to make a textbox with in there a word when i click on a button that word needs to convert into numbers useing charAt and that number needs to get +2 and than converted back into words and that word needs to get alerted i dont know what to do i find this really hard i made a function that is useless but i just want to show you what i did please help :)
function codeer(){
var woord2 = document.getElementById("woord")
var woordterug = woord2.charAt(0)
var woord234 = document.getElementById("woord");
var woord23 = woord234.charAt(str.length+2);
}

You could get the char code with String#charCodeAt from the character add two and build a new string with String.fromCharCode.
function codeer() {
var woord = document.getElementById("woord").value,
coded = '',
i;
for (i = 0; i < woord.length; i++) {
coded += String.fromCharCode(woord.charCodeAt(i) + 2);
}
console.log(coded);
}
<input id="woord" /> <button onclick="codeer()">cooder</button>

You should search the internet for a JavaScript rot13 example. In that code, you just need to replace the 13 with a 2, and it should work.

Related

string random characters in a for loop

Im having trouble with the following code while trying to make a random password generator. The first two lines seem to be working as intended. I confirmed this with the following:
If I replace the "passwordText = passwordText.concat(character:" with "console.log(character)" it works in the console. Picks a random char from an array and will console log it the desired amount of times.
However, on line 3 I'm trying to concat these random chars into one string. Any ideas? I'm getting a TypeError: Cannot read property 'concat'. All variables are declared.
for (var i = 0; i < inputLength; i++) {
character = finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
passwordText = passwordText.concat(character);
}
passwordText = passwordText.concat(character);
I would appreciate any guidance on this. Many thanks, Steven.
PS. This is my first week with JS, go easy on me! :)
strings don't have a concat method unlike arrays. What you need is +=:
passwordText += character;
Edit: concat not push
Thanks everyone for your help. Below worked. I also give password text a value as mentioned by caTS.
// function to return the password
function generatePassword() {
for (var i = 0; i < charLength; i++) {
passwordText += finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
} return passwordText
}

Can't get values past array[0] to translate properly

Okay, to start with I should mention this is a very small personal project, and I've only have a handful of coding classes several years ago now. I can figure out a lot of the (very) basics, but have a hard time troubleshooting. I'm in a little bit over my head here, and need a dumbed down solution.
I'm trying to put together a VERY simple translator that takes in a word or sentence from the user via a text input box, puts each word of the string into an array, translates each word in order, then spits out each translated word in the order it was input. For example, typing "I like cats" would output "Ich mag Katze" in German.
I've got most of it, but I CAN'T get anything but the first array element to translate. It comes out like "Ich like cats".
I've used a loop, probably because I'm an amateur and don't know another way of doing this, and I'd rather not use any libraries or anything. This is a very small project I want to have a couple of friends utilize locally; and I know there has to be some very simple code that will just take a string, put it into an array, swap one word for another word, and then output the results, but I'm damned if I can make it work.
What I currently have is the closest I've gotten, but like I said, it doesn't work. I've jerry-rigged the loop and clearly that's the totally wrong approach, but I can't see the forest for the trees. If you can help me, please make it "Javascript for Babies" picture book levels of simple, I cannot stress enough how inexperienced I am. This is just supposed to be a fun little extra thing for my D&D group.
function checkForTranslation(input, outputDiv) {
var input = document.getElementById("inputTextField").value;
var outputDiv = document.getElementById("translationOutputDiv");
input = input.toLowerCase();
//puts user input into an array and then outputs it word by word
const myArray = input.split(" "); //added .split, thank you James, still otherwise broken
let output = "";
let translation = "";
for (let i = 0; i < myArray.length; i++) {
output += myArray[i]; //up to here, this works perfectly to put each word in the string into an array
//prints all words but doesnt translate the second onwards
translation += myArray[i];
if (output == "") {
//document.getElementById("print2").innerHTML = "Translation Here";
}
else if (output == "apple") {
translation = "x-ray";
}
else if (output == "banana") {
translation = "yak";
}
else {
translation = "???";
}
output += " "; //adds a space when displaying original user input
} // END FOR LOOP
document.getElementById("print").innerHTML = output; //this outputs the original user input to the screen
document.getElementById("print3").innerHTML = translation; //this should output the translated output to the screen
} // END FUNCTION CHECKFORTRANSLATION
What it looks like
P.S. I'm not worried about Best Practices here, this is supposed to be a quickie project that I can send to a couple friends and they can open the HTML doc, saved locally, in their browser when they want to mess around with it if they want their half-orc character to say "die by my hammer!" or something. If you have suggestions for making it neater great, but I'm not worried about a mess, no one is going to be reading this but me, and hopefully once it's fixed I'll never have to read it again either!
Since it is a manual simple translation, you should just create a "dictionary" and use it to get the translations.
var dictionary = {
"apple": "x-ray",
"banana": "yak"
}
function checkForTranslation() {
var input = document.getElementById("inputTextField").value.toLowerCase();
var words = input
.split(' ') // split string to words
.filter(function(word) { // remove empty words
return word.length > 0
});
var translatedWords = words.map(function(word) {
var wordTranslation = dictionary[word]; // get from dictionary
if (wordTranslation) {
return wordTranslation;
} else { // if word was not found in dictionary
return "???";
}
});
var translatedText = translatedWords.join(' ');
document.getElementById("translationOutputDiv").innerHTML = translatedText;
}
document.getElementById('translate').addEventListener('click', function() {
checkForTranslation();
});
<input type="text" id="inputTextField" />
<button id="translate">translate</button>
<br/>
<hr />
<div id="translationOutputDiv"></div>
Or if you want it a little more organized, you could use
const dictionary = {
"apple": "x-ray",
"banana": "yak"
}
function getTranslation(string) {
return string
.toLowerCase()
.split(' ')
.filter(word => word)
.map(word => dictionary[word] || '???')
.join(' ');
}
function translate(inputEl, outputEl) {
outputEl.innerHTML = getTranslation(inputEl.value);
}
document.querySelector('#translate').addEventListener('click', function() {
const input = document.querySelector('#inputTextField');
const output = document.querySelector('#translationOutputDiv');
translate(input, output);
});
<input type="text" id="inputTextField" />
<button id="translate">translate</button>
<br/>
<hr />
<div id="translationOutputDiv"></div>

Comparing string values and showing correct 'answers' in javascript

I am fairly new to Javascript and am trying to learn to write a program that shows a text in one language (eg. Spanish) and has an input box, where the user will type the translated (eg. English) word. The user input would then be compared to the translated word to see if they are the same. I also want to allow some tolerance in case the user inputs a word without an accent if there is supposed to be one (eg. esta instead of está) it won't be counted wrong. If they are not the same I want to be able to show the correct word compared to what the user put. I've been trying to work on this for quite some time but have been getting stuck frequently (for instance, when I run the other function to check the values it opens a new instance when I want it all to be displayed on the same page). Any help with this would be greatly appreciated. Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Flashcards</title>
</head>
<body>
<script>
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
</script>
<p>English Translation: <input id="english_word" type="text" name="LastName" value="" ></p>
<input type="button" id="myBtn" onclick="check()" value="Check">
<input type="button" id="button" onclick="differentword()" value="Different Word">
<script>
function check()
{
var english_word= document.getElementById('english_word').value;
if (english_word == English) {
document.write("Correct");
}
else {
document.write("Wrong: ");
document.write(Spanish+" in English is "+English);
}
}
function differentword() {
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
}
</script>
</body>
</html>
Or, if you want to see how it runs, you can check it out here https://code.sololearn.com/WXHZ5aAcE3dg/#html.
You got 2 problems here.
You haven't set the current <input id="english_word" type="text" name="LastName" value=""> any value at all (by both html/js). You should set it to the current word (as a string) to manipulate it later.
the if statement if (english_word == English) is broken because it checks if english word, which is a string, equals to an array. and its not, and will never be.
However, checking if the current string word equals to a string, is not a good way in my option. I would like better to use an index to current word that is showing and manipulating that index.
What I suggest is you fix the above by using a new variable: current_word_index, so you can use it in program to check the answer by knowing the current word that is showing.
This next code is just an example of how to currently retrieve by index from arrays:
var current_word_index = 0; // this 0 will change to rand()
var english_word = ["hi","bye"];
english_word[current_word_index];
// english_word will be string "hi".
Here's my full answer:
https://fiddle.jshell.net/j44fjh35/15/
Summary of your question
My understanding is your trying to test the users knowledge on a secondary language ie: Spanish, French etc.
Solution
Switch or If statements are ways to test and compare variables against one another
what you will need to do is first of all convert the string variable to lowercase to ensure that what ever the user types in is always the same.
You will also need to fix some of your code.
So lets look at that first...
var number = parseInt((Math.random()*1));
var spanish_word = ["hola","adios"];
spanish_word is an array which starts from 0 not 1.
Your randomly generated number stored as "number", will equally need to be 0 or 1, simple integer will be sufficient.
Unless your submitting this to a server to be handled by some backend code in PHP or ASP etc, you dont need the "name" attribute here
name="LastName"
You are then over-riding the array
At the start you are setting the array with the following values
var english_word = ["hi","bye"];
But when you click the button to check if you have the right answer
You are erasing the above and telling it to be what ever the user typed in
var english_word= document.getElementById('english_word').value;
There is no need to keep setting and un-setting the array
Try to use better naming convensions for your variables
abbreviate them with what data types they are:
arrEnglishWord to symbolise its an array
strEnglishWord to symbolise it is a string
intEnglishISOCode to symbolise a numerical integer
blEnlish to symbolise a boolean
A lot of code repetition:
Using the an event listener you can save the code repetition
document.addEventListener("DOMContentLoaded", differentword, false);
will make the function differentword run when the page loads, allowing you to get rid of the repeated code at the top
Solution
We need to make the comparison fair (ie not case sentisive)
var strAnswerGiven = english_word.toLowerCase();
var strCorrectAnswer = English.toLowerCase();
if (strAnswerGiven == strCorrectAnswer) {
var arrSpanishWords = ["Hola", "Adios", "Purta", "Luz"];
var arrEnglishWords = ["Hello", "Goodbye", "Door", "Light"];
var strWord = undefined;
var divAnswer = undefined;
function funCheck(elName){
var stAnswer = document.querySelector("#" + elName).value;
var stAnswerGiven = stAnswer.toLowerCase();
var stAnswerExpected = strWord.toLowerCase();
if (stAnswerGiven == stAnswerExpected){
divAnswer.style.color = "#0F0";
divAnswer.innerHTML = "Correct";
}else{
divAnswer.style.color = "#F00";
divAnswer.innerHTML = "Wrong";
}
}
function funNewQuestion(){
var intRandomQNum = parseInt(Math.random() * arrSpanishWords.length);
var elDisplayQuestion = document.getElementById("divWord");
divAnswer = document.getElementById("divAnswerIs");
divAnswer.innerHTML = "";
elDisplayQuestion.innerHTML = arrSpanishWords[intRandomQNum];
strWord = arrEnglishWords[intRandomQNum];
}
document.addEventListener("DOMContentLoaded", funNewQuestion(), false);
Word: <div id="divWord"></div><div id="divAnswerIs"></div>
Answer: <input type="text" id="frmTxtAnswer">
<button id="check" onclick="funCheck('frmTxtAnswer')">Check Answer</button>
<button id="check" onclick="funNewQuestion()">Next Question</button>

I want to obtain a certain part of text from a large webpage using Javascript, how do I?

There is a certain webpage which randomly generates a number, for example "Frequency : 21". I am trying to create a script which takes the number, 21, and compares it to another variable, then to an if else function. Basically, I've completed most of it, but I can't obtain the number 21. And since it is random, I can't put in a fixed value.
Can anyone help me out?
My code goes like:
setTimeout(MyFunction,5000)
function MyFunction(level,legmin) {
var level = x
var legmin = 49
if (level <= legmin) {
location.reload(true)
}
else {
alert("Met requirements.")
}
where the address of the text I want is:
html>body>div#container>div#contentContainer>div#content>
div#scroll>div#scrollContent>div>div>div#pkmnappear>form>p (x in the code above).
A quick-n-dirty solution without regex.
var lookFor = "Frequency : ";
var text = document.querySelector("#pkmnappear>form>p").textContent;
var level = text.substr(text.indexOf(lookFor) + lookFor.length).split(" ")[0];
This assumes the number will be followed by a space

parse a textarea in substrings based on line breaks in Javascript

I have a text area that I need to parse. Each new line needs to be pulled out and an operation needs to be performed on it. After the operation is done the operation needs to be run on the next line. This is what I have at the moment. I know the indexOf search won't work because it's searching character by character.
function convertLines()
{
trueinput = document.getElementById(8).value; //get users input
length = trueinput.length; //getting the length of the user input
newinput=trueinput; //I know this looks silly but I'm using all of this later
userinput=newinput;
multiplelines=false; //this is a check to see if I should use the if statement later
for (var i = 0; i < length; i++) //loop threw each char in user input
{
teste=newinput.charAt(i); //gets the char at position i
if (teste.indexOf("<br />") != -1) //checks if the char is the same
{
//line break is found parse it out and run operation on it
userinput = newinput.substring(0,i+1);
submitinput(userinput);
newinput=newinput.substring(i+1);
multiplelines=true;
}
}
if (multiplelines==false)
submitinput(userinput);
}
So for the most part it is taking the userinput. If it has multiply lines it will run threw each line and seperatly and run submitinput. If you guys can help me I'd be eternally thankful. If you have any questions please ask
Line breaks within the value of a textarea are represented by line break characters (\r\n in most browsers, \n in IE and Opera) rather than an HTML <br> element, so you can get the individual lines by normalizing the line breaks to \n and then calling the split() method on the textarea's value. Here is a utility function that calls a function for every line of a textarea value:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("your_textarea");
actOnEachLine(textarea, function(line) {
return "[START]" + line + "[END]";
});
If user is using enter key to go to next line in your text-area you can write,
var textAreaString = textarea.value;
textAreaString = textAreaString.replace(/\n\r/g,"<br />");
textAreaString = textAreaString.replace(/\n/g,"<br />");
textarea.value = textAreaString;
to simplify the answers, here is another approach..
var texta = document.getElementById('w3review');
function conv (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
<textarea id="targetted_textarea" rows="6" cols="50">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="conv('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>

Categories

Resources