Looping Through an Array of Characters - javascript

I would like to loop an array for a specific set of characters that is constantly changing. From there on I want to toggle case the letters, and I've been told to use this specific code but I can't get it to work. The code MUST loop through an array of characters, where the characters are coming from an "input" textbox. How can I fix this?
I should mention that I'm doing this for class in high school, so I'm no where near perfect at coding.
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var i = document.getElementById("input").value.length;
var word = document.getElementById("input").value;
var chop =new array(i);
for (a=i; a <= i; a++) {
character[i] = word.slice(i-1,i)
if (character[i] == character[i].toUpperCase;){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
var final
for (a=i; a <= i; a++) {
final += character[i];
}
document.getElementById("output").value = final
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase(this.form)">Toggle Case<br/>
</form>
</body>
</html>

Maybe you should take a look at some api's and howtos but here is your code:
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var text = document.getElementById("input").value;
var character = new Array(text.length);
for (i=0, a = text.length; i < a; i++) {
character[i] = text[i];
if (character[i] == character[i].toUpperCase){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
document.getElementById("output").value = character.join('');
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase()">Toggle Case<br/>
</form>
</body>
</html>

function toggleCase() {
var str = document.getElementById("input").value;
for (var i=0; i<str.length; i++) {
str[i] = (str[i]==str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase());
}
document.getElementById("output").value = str;
}
that's a for loop that does the job. and remember .toUpperCase and .toLowerCase are functions

You might want to take a look at the String's split method.
var str = 'foo bar baz';
The simplest way to convert a string into a char array is by passing an empty string into the split method.
var charArray = str.split(''):
// charArray === ['f','o','o' ... 'b','a','z'];
Also a FYI, passing a space character into split will give you an array of words.
var wordArray = str.split(' ');
// wordArray === ['foo', 'bar', 'baz'];
I'm a little unclear what you have to solve but it looks like you want a function convert upper case letter into lowercase letters and vise versa.
var userInput = document.getElementById('someTextBox');
// If you want to be fancy you could use JQuery
// var userInput = $(#someTextBox').value()
function toggledCase( str ) {
var characters = str.split('');
// The split method still uses iteration so should be able to say it
// satisfies the argument of looping through each character.
// Split just provides a good abstraction to interface with.
var toggledCharacters = [];
var i;
var ch;
for( i in characters ) {
// For in loops on strings will return the indexes instead
// of the characters
ch = characters[i];
if( ch.toUpperCase() === ch ){
toggledCharacters.push( ch.toLowerCase() );
} else {
toggledCharacters.push( ch.toUpperCase() );
}
// If you like one-liners,
// the conditional if statement could be replace with a ternay statement.
// toggledCharacters.push( ( ch.toUpperCase() === ch ) ?
// ch.toLowerCase() : ch.toUpperCase();
}
return toggledCharacters;
}
My toggledCharacters method only returns an array of characters, so if you want back as a string you could make a for loop;
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = '';
var i, ch;
for ( i in arr ) {
str += arr[i]; // += is just a short hand notation of saying
// str = str + arr[i];
}
If you are lazy and like one-liners, take a look at functional programming. It's kinda out of scope since you are still in High School.
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = arr.reduce( function(str, ch) {
return str + ch;
} );
Anyway, this looks a lot cleaner to me than what the teacher outlined.
function toggledCharacters(input) {
input = input.split('');
var output = [];
var i, ch;
for( i in input ) {
output.push( ( input[i].toUpper() === input[i] ) ?
input[i].toLower() : input[i].toUpper()
);
}
return output.reduce(
function(str, ch) {
return str + ch;
}
);
}
Edit:
Oh, I just notice that nowhere in that code the is the check's box boolean value being evaluated.
var checkBox = document.getElementByName('toggle');
var inputTextBox = document.getElementById('input');
var outputTextBox = document.getElementById('output');
var result = inputTextBox.value;
if( checkBox.checked ) {
result = toggleCase( result );
}
outputTextBox.value = result;
Oh another FYI since you are a beginner. Make sure you know to use the browser's console.
If you are on Firefox, grab the firebug app.
Chrome, press Ctrl-Shift-C.
IE has one as well, I just don't care to ever use it.
The console makes it easier to experiment with JS then compared to making html demo page and assuming the code is working as it should.
Plus, these developer tools can show you underlying methods of an object. It makes for a great and quick way to learn JS.

Related

Any alternative way of using this .length & .split()?

I want to split lower, upper & also the value of textBox without using .split() and also I want
to find the length of the string without using .length. Can anybody solve my problem I am tried but
I cannot find the exact logic for this problem.
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
function toUpper(input) {
var upperCase = uppercase.split(""); //other way to split uppercase
var lowerCase = lowercase.split(""); //other way to split lowercase
var inputText = input.split(""); //other way to split input
var newText = "";
var found;
for (var i = 0; i < inputText.length; i++) { //not using .length to other way to find the size of inputText
found = false;
for (var ctr = 0; ctr < lowerCase.length; ctr++) { //not using .length other way to find the size of lowerCase
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
You can count the length of a string using the array function reduce.
Reduce loops over all elements in an array and executes a function you give it to reduce it to one value, you can read more here.
To get reduce working on strings, you need to use Array.from, like this:
Array.from(lowerCase).reduce((sum, carry) => sum + 1, 0) // 26
Reduce accepts a starting argument, which we set to zero here.
This way you do not need to use the split or length functions.
You don't need to check if the input is in a string either, you can use charCodeAt() and fromCharCode().
If you take your input and loop through it using Array.from() then forEach, you can get something which looks like this:
function print() {
const input = document.querySelector('#input').value;
document.querySelector('#target').value = stringToUpper(input);
}
function stringToUpper(input) {
let output = "";
Array.from(input).forEach(char => output += charToUpper(char));
return output;
}
function charToUpper(char) {
let code = char.charCodeAt(0);
code >= 97 && code <= 122 ? code -= 32 : code;
return String.fromCharCode(code);
}
<div>
<input id="input" placeholder="enter text here">
</div>
<button onclick="print()">To Upper</button>
<div>
<input id="target">
</div>
The key line is where we take the output and add the char (as upper) to it:
output += charToUpper(char)
If you don't know about arrow functions, you can read more here
This line:
code >= 97 && code <= 122 ? code -= 32 : code;
is just checking if the char is lower case (number between 97 and 122) and if so, subtracting 32 to get it to upper case.
The reason it is subtract not add is in utf-16, the chars are laid out like this:
ABCDEFGHIJKLMNOPQRTUWXYZabcdefghijklmnopqrtuwxyz
See here for more
I don't know what you mean by "split the value of textBox", but one way to determine the length of a string without using .length would be to use a for...of loop and have a counter increment each time it runs to keep track of the number of characters in the string.
let string = 'boo'
let lengthCounter = 0
for (let char of string) {
lengthCounter++
}
//lengthCounter = 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
You can define your own split and length functions:
function mySplit(a){
var counter = 0;
rslt = [];
var val = a[counter];
while(typeof val != "undefined"){
rslt.push(a[counter]);
counter ++;
val = a[counter];
}
return rslt;
}
function myLength(a){
var counter = 0;
var val = a[counter];
while(typeof val != "undefined"){
counter ++;
val = a[counter];
}
return counter;
}
Your function now should be like:
function toUpper(input) {
var upperCase = mySplit(uppercase);
var lowerCase = mySplit(lowercase);
var inputText = mySplit(input);
var newText = "";
var found;
for (var i = 0; i < myLength(inputText); i++) {
found = false;
for (var ctr = 0; ctr < myLength(lowerCase); ctr++) {
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
The simplest way would be to just use the build in function of javascript .toUpperCase() (see example 1). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
Else if you insist on using a for.loop you may do so aswell (see example two). You do not need the split() function since a string already is an arrayof characters. Also be aware that not all characters in the web have lowercase counterparts, so the logic itself is flawed.
//REM: This lines are not required.
/*
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
*/
//REM: Version 1 (using string.toUpperCase())
(function toUpper1(input){
var tReturn = (input || '').toUpperCase();
console.log('toUpper1', tReturn);
return tReturn
}('abcDEFghiJKL'));
//REM: Version 2 (using your way)
(function toUpper2(input){
var tReturn = '';
if(input && input.length){
for(let i=0, j=input.length; i<j; i++){
tReturn += (input[i] === input[i].toLowerCase()) ? input[i].toUpperCase() : input[i]
}
};
console.log('toUpper2', tReturn);
return tReturn
}('abcDEFghiJKL'));

Count the numbers in an array then write them out

It's still old school JS week for newbies at the academy.
I have created an input that makes it possible for a user to put some numbers in a input to write out an array.
Now what I'm trying to do next is writing out a paragraph with a counter for each number, like with how many times the number has been used.
If the array was [0,0,1,1,1,2,2,2,2];
And I want it to write it out something like this:
"How many times does your number appears in your array:"
0: 2
1: 3
2: 4
So far I got it to print out the numbers from the input, but I can't find a way to make it write out like above.
var numbers = [];
function numbarray() {
numbers.push(document.getElementById("box").value);
document.getElementById("text1").innerHTML = "";
document.getElementById("text1").innerHTML += numbers.join(", ");
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
After tinkering, failing and googling since yesterday morning I've figure I try out SO again, since I've learned more from this site then I could ever imagine.
Thank you so much in advance
This solution features an object for counting the frequency of the numbers with a focus of occurrence.
function count() {
var numbers = document.getElementById("box").value
.split(',')
.map(Number)
.filter(isFinite),
distribution = numbers.reduce(function (r, a) {
r[a] = (r[a] || 0) + 1;
return r;
}, {});
document.getElementById("text1").innerHTML = numbers.join(", ");
document.getElementById("distribution").innerHTML = Object.keys(distribution)
.sort(function (a, b) {
return distribution[b] - distribution[a];
})
.map(function (k) {
return k + ': ' + distribution[k];
}).join('<br>');
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="count()" /><br>
Your array: <span id="text1"></span><br>
How many times does your number appears in your array:<br>
<div id="distribution"></div>
var numbers = [];
function numbarray() {
numbers = [];
numbers = numbers.concat(document.getElementById("box").value.split(','));
var hash = {};
for(var i=0; i<numbers.length; i++) {
if (typeof hash[numbers[i]] === 'undefined') hash[numbers[i]] = 0;
hash[numbers[i]] ++;
}
document.getElementById("text1").innerHTML = "";
for(var k in hash) {
document.getElementById("text1").innerHTML += k + ': ' + hash[k] + '\n';
}
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
function numbarray() {
var nums = {}; // Use a dictionary for tallying numbers
var numStrings = document.getElementById("box").value.split(","); // Split by commas
// Just tally up each number
for (var i = 0; i < numStrings.length; i++){
var num = numStrings[i];
if (num in nums){
nums[num]++;
}
else {
nums[num] = 1;
}
}
var keys_ = Object.keys(nums); // Get the keys and sort them
keys_.sort();
document.getElementById("text1").innerHTML = "<br>"; // Reset the html
for (var key in keys_){
// Print out each number and its tally
document.getElementById("text1").innerHTML = key + ": " + nums[key] + "<br>";
}
}
Not sure if I totally understand what you are trying to do, but if you want to display the count of each number, you should first get the count of each number, then place them in your DOM, through a function such as:
var numbers = [];
var numbersObject = {};
function numbarray() {
numbers.push(document.getElementById("box").value);
//put numbers in object to get count of each
for(i=0; i<numbers.length; i++){
if(numbersObject[numbers[i]]){
numbersObject[numbers[i]]++
}else{
numbersObject[numbers[i]] = 1
}
}
//prepare HTML
var content = '';
for(var key in numbersObject){
content += key + ':' + numbersObject[key] + '<br>';
}
document.getElementById("text1").innerHTML = content
}

Count occurance of a letter or a word in a sentence

I wonder how I can find how many characters, example e, in a text using a for loop and a increasing substring to go through the whole text.
This is what I got so far.
HTML:
<p id="paragraph"> this is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<input type="text" id="text"/> <input type="button" value="search" onclick="search()"/>
<p id="howmany"></p>
JavaScript:
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0);
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementById("howmany").innerHTML = ("The result is" + count)
}
I only get how many characters there is in the text, but I want to find how many e or is or whatever there is in the text. I know there is something missing but what?
There's no need for a loop for this - you can just use a regex and count the matches:
string.match(/e/g).length
string.match(/is/g).length
That said, there are a bunch of other errors in your code:
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0,text.lenght); // should be length; or else not needed at all
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementsById("howmany").innerHtml = ("The result is" + count) // it's getElementById, not getElements; it's innerHTML, not innerHtml
}
Also: onclick, on clickOn.
My own take on this problem:
function howMany () {
var needle = document.getElementById('text').value.trim(),
textProp = 'textContent' in document ? 'textContent' : 'innerText',
haystack = document.getElementById('paragraph')[textProp].trim(),
result = haystack.match(new RegExp(needle, 'g'));
document.getElementById('howmany')[textProp] = result ? result.length : 0;
}
document.querySelector('input[type=button]').addEventListener('click', howMany);
#howmany::before {
content: 'Matches found: ';
}
#howmany:empty::before {
content: '';
}
<p id="paragraph">This is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<label>String to find: <input id="text" placeholder="what are you looking for?" /></label>
<input type="button" value="search" />
<p id="howmany"></p>
References:
document.getElementById().
document.querySelector().
EventTarget.addEventListener().
in operator.
JavaScript regular expressions.
String.prototype.match().
String.prototype.trim().

Make cipher code in javascript using for loop and array?

I need to use a for loop to add 2 random letters to the string inputed into the text box and returned in the encrypted string box when the button is clicked.
So, for example, if cat was inputted it could return like cynarwtpp. I am new to for loops and unsure how to proceed from here, I need to use a for loop that will cycle through the alphabet array. any help would be greatly appreciated.
Javascript:
<script type="text/javascript">
var uncoded_array = uncoded.split("");
var coded_str = "";
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
</script>
Html:
<form action="">
Enter a String: <input type="text" name="uncoded" ></br>
<input type="button" value="cipher" onClick=document.forms[0].coded.value= ></br>
Encrypted String: <input type="text" name="coded" ></br>
This is what I would do
html
Enter a String: <input type="text" id="uncoded" />
<input type="button" value="cipher" onclick="cypher(); return false;" />
Encrypted String: <input type="text" id="coded" />
js
function cypher() {
var coded = document.getElementById('coded');
var uncoded = document.getElementById('uncoded');
coded.value = uncoded.value.split('').map(function (char) {
return char + randomLetter() + randomLetter();
}).join('');
}
function randomLetter() {
return Math.random().toString(36).replace(/[^a-zA-Z]/gi, '')[0];
}
Here is a simple approach.
1) From this answer I learned to pick random element from array.
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
In your case 2 random letter from array.
2) In the for iteration, I have taken a string length and used to add the random element after each letter and concatenated together.
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
var original = "cat";
var encrypted = "";
for (var i=0; i<original.length; i++ ) {
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
encrypted += original[i] + item1 + item2;
}
alert(encrypted);
JSFiddle
Here's a simple function that performs the string operation. Just feed it the value of the first form input, and dump its result into the second form input.
function cipher(str) {
var rand,
output = '',
chars = 'abcdefghijklmnopqrstuvwxyz';
for (i=0; i<str.length; i++) {
output += str[i];
for (j=0; j<2; j++) {
output += chars[Math.floor(Math.random() * chars.length)];
}
}
return output;
}
cipher('cat');

Test a Textarea for All Keywords in an Array

I found a variation on this code elsewhere in StackOverflow. It takes all words from a textarea and converts them into a regular expression. It then tests an array to see if all the words in the regex are contained in the array:
<textarea id="inputtext" type="text"></textarea>
<input id="searchbutton" type="button" value="Click me" />
var links = new Array("taxi","Alpha","runway");
$("#searchbutton").click(function () {
var query = $("#inputtext").val();
var querywords = query.split(',');
for (var i = 0; i < querywords.length; i++) {
var regex = new RegExp('(?=.*\\b' + querywords[i].split(' ').join('\\b)(?=.*\\b') + '\\b)', 'i', 'g');
for (var j = 0; j < links.length; j++) {
if (regex.test(links[j])) {
console.log("Correct");
}
}
}
});
How can I reverse the process so the program returns "true" if the textarea words includes all of the keywords within the array? For example, if the textarea had the sentence "Taxi to the runway via taxiway alpha," and the array named "links" contained the keywords "taxi" "alpha" and "runway", the program would return "true".
That script you have seems to check if any of the words appears somewhere in the array. What you want is the every Array method:
var text = "Taxi to the runway via taxiway alpha",
links = ["taxi", "alpha", "runway"];
console.log( links.every(function(word) {
return new RegExp("\\b"+word+"\\b", "i").test(text);
}) ); // true
The methods provided by other answers are simple, but they could be more efficient.
It's almost always better to use an object as a map to speed up lookups instead of having to search the entiry array everytime.
var words = ['word1', 'word2'],
wordsMap = 'text area content, word1 and word2'.split(/\W+/).reduce(function (obj, word) {
obj[word] = true;
return obj;
}, {}),
areWordsAllContained = words.every(function (word) {
return wordsMap[word.toLowerCase()];
});
console.log(areWordsAllContained); //true
EDIT: I've changed the splitting regex from \s+ to \W+ to make sure that it splits on every non-word characters.
A non-regex way would be:
var arr = ['word1', 'word2'], haystack = textArea.value.toLowerCase().split(/\s+/);
var result = true, i = 0;
for(i=0; i<arr.length; i++) {
if(haystack.indexOf(arr[i].toLowerCase()) === -1) {
result = false;
break;
}
}

Categories

Resources