For Loops isn't working properly with comparison operators - javascript

Having trouble getting my code to log Scooby Doo! (as testing as I move forward in my code) Instead I always get the alert!
I have the user entering data of numbers in an array eg. [1 2 3 4] and I am trying to get the alert to pop up when someone puts extra spaces in the array to try again.
And if they haven't added extra spaces to log Scooby Doo!
document.getElementById("button").addEventListener("click", myExcelFuns);
function myExcelFuns() {
var userInputStr = document.getElementById("numbers").value;
if (userInputStr) {
console.log(userInputStr);
userInputStr = userInputStr.trim();
let userNumberArray = userInputStr.split(" ");
console.log(userNumberArray);
let result;
let newArray = [];
for (let i = 0; i < userNumberArray.length; i++) {
let newArrayValues = parseInt(userNumberArray[i]);
newArray.push(newArrayValues);
}
console.log(newArray);
//Here is the trouble
let finalArray = [];
if (newArray === Number && newArray != ""){
for (let i = 0; i < newArray.length; i++) {
console.log("Scooby Doo");
finalArray.push(newArray);
}
} else {
alert("Only one space between numbers please!")
}
}

This expression is wrong and it will never be true:
if (newArray === Number && newArray != ""){
if (newArray === Number && newArray != ""){
for (let i = 0; i < newArray.length; i++) {
console.log("Scooby Doo");
// Here you'll push whole newArray everytime it runs, I guess it's wrong as well
finalArray.push(newArray);
}
} else {
alert("Only one space between numbers please!")
}
I've wrote your code using some features from ES6 to show you how easy is our life using these features.
//Here you must pass a valid Id
document.getElementById("myButton").addEventListener("click", myExcelFuns);
function myExcelFuns() {
var userInputStr = document.getElementById("numbers").value;
if (userInputStr) {
userInputStr = userInputStr.trim();
let userNumberArray = userInputStr.split(" ");
//check if some value into arrya is not a number
const isThereSomeInvalidNumber = userNumberArray.some(x => isNaN(x))
if(isThereSomeInvalidNumber){
alert("Only one space between numbers and valid numbers please!");
//here if it's invalid you can clear the input
document.getElementById("numbers").value = "";
}
//map runs into your array and return a new array
const newArray = userNumberArray.map(x => {
return parseInt(x)
})
console.log(newArray);
}
}
<button id="myButton">
click me
</button>
<input type="text" id="numbers" />
I hope it can inspire you =)

Related

How can I extract all contained characters in a String? [duplicate]

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Why does this function not work within the eventListener?

I am just starting with JavaScript and for my first project I am trying to display a working calculator using JS, HTML and CSS. I am just one step away from it finally handling easy operations but for some reason my "solver"-function does not work when hitting the Enter-button.
I already tried out all the functions in a "test.js" console.logging the results and everything worked perfectly. But for some reason it won't work when combining it with the eventListener and trying to display it within the textfield. I also tried simpler functions and displaying only variables in the textfield which works. It is just the solver-function that won't.
I will attach my code - most of you would definitely code a calculator much different and especially much shorter than the way I did it but I am proud I got this far, so please don't judge me too harshly! :D
First the declaration of functions which worked perfectly in the test.js. The solver was originally designed to return the previous 4 functions in a nested way but I thought this might be the problem, so I changed it.
function adds(num1, num2) {
return num1+num2;
};
function subs(num1, num2) {
return num1-num2;
};
function muls(num1, num2) {
return num1*num2;
};
function divis(num1, num2) {
return num1/num2;
};
//Creates an array with string elements.
function createArray(string) {
let array = [];
for(let element of string) {
array.push((element));
}
return array;
};
//Returns an array where numbers are joint within one element (e.g. '1','2' becomes '12').
function joinNums(array) {
let numArray = [''];
let index = 0;
for (i=0; i < array.length; i++) {
if (isNaN(parseInt(array[i]))) {
index ++;
numArray.push(array[i]);
index++;
numArray[index]=[''];
continue;
}
numArray[index] =numArray[index] + array[i];
}
return numArray;
};
//Returns an array where all elements with numbers in them are changed to proper numbers instead of strings.
function makeNums(array) {
let numArray = [''];
let index = 0;
for (i=0; i < array.length; i++) {
if (isNaN(parseInt(array[i]))) {
index ++;
numArray.push(array[i]);
index++;
numArray[index]=[''];
continue;
}
numArray[index] = parseInt(array[i]);
}
return numArray;
};
//Calculates the array that is provided and returns a single number as solution.
function operate(array) {
let solution = array[0];
for(let iOp = 1; array.length >= iOp; iOp=iOp+2) {
if(array[iOp] === '+') {
solution = adds(solution, array[iOp+1]);
}
if(array[iOp] === '-') {
solution = subs(solution, array[iOp+1]);
}
if(array[iOp] === '*') {
solution = muls(solution, array[iOp+1]);
}
if(array[iOp] === '/') {
solution = divis(solution, array[iOp+1]);
}
}
return solution;
};
//Takes a string (meant to be the value of a textfield) and returns the solution by calling all previously declared helper functions.
function solver(string) {
let cr = createArray(string);
let jo = joinNums(cr);
let ma = makeNums(jo);
let op = operate(ma);
return op;
};
Now on to the input field and hitting the enter-button:
//This is the enter-button
let enter = document.getElementById("enter");
//This is the textfield where calculations are entered. The textfield is then meant to be changed to display the operations result.
let textfield = document.getElementById("resultLn");
//The eventlistener.
enter.addEventListener("click", () => {
textfield.value = solver(textfield.value);
});
You do not use let statement at the for cycles i operand (at function joinNums, makeNums).
In addition at function operate, you can use switch.
Hi,
Your calculator code works well, If there was a problem, checkout your html.
I test with some operations and it works well. If there any operation doesn't work, please type this operation to help you
//This is the enter-button
let enter = document.getElementById("enter");
//This is the textfield where calculations are entered. The textfield is then meant to be changed to display the operations result.
let textfield = document.getElementById("resultLn");
//The eventlistener.
enter.addEventListener("click", () => {
textfield.value = solver(textfield.value);
});
function adds(num1, num2) {
return num1+num2;
};
function subs(num1, num2) {
return num1-num2;
};
function muls(num1, num2) {
return num1*num2;
};
function divis(num1, num2) {
return num1/num2;
};
//Creates an array with string elements.
function createArray(string) {
let array = [];
for(let element of string) {
array.push((element));
}
return array;
};
//Returns an array where numbers are joint within one element (e.g. '1','2' becomes '12').
function joinNums(array) {
let numArray = [''];
let index = 0;
for (i=0; i < array.length; i++) {
if (isNaN(parseInt(array[i]))) {
index ++;
numArray.push(array[i]);
index++;
numArray[index]=[''];
continue;
}
numArray[index] =numArray[index] + array[i];
}
return numArray;
};
//Returns an array where all elements with numbers in them are changed to proper numbers instead of strings.
function makeNums(array) {
let numArray = [''];
let index = 0;
for (i=0; i < array.length; i++) {
if (isNaN(parseInt(array[i]))) {
index ++;
numArray.push(array[i]);
index++;
numArray[index]=[''];
continue;
}
numArray[index] = parseInt(array[i]);
}
return numArray;
};
//Calculates the array that is provided and returns a single number as solution.
function operate(array) {
let solution = array[0];
for(let iOp = 1; array.length >= iOp; iOp=iOp+2) {
if(array[iOp] === '+') {
solution = adds(solution, array[iOp+1]);
}
if(array[iOp] === '-') {
solution = subs(solution, array[iOp+1]);
}
if(array[iOp] === '*') {
solution = muls(solution, array[iOp+1]);
}
if(array[iOp] === '/') {
solution = divis(solution, array[iOp+1]);
}
}
return solution;
};
//Takes a string (meant to be the value of a textfield) and returns the solution by calling all previously declared helper functions.
function solver(string) {
let cr = createArray(string);
let jo = joinNums(cr);
let ma = makeNums(jo);
let op = operate(ma);
return op;
};
<input type="text" id="resultLn">
<button id="enter">Enter</button>

Check if String has sequential or repeated characters in javascript (underscore)

I have code that I am trying to refactor. Im new to javascript so Im tring to make more readable code using functions in libraries like underscore.
The function below can detect when string
contains 3 or more ordered characters such as (234, efg, LmN)
and
when string contains 3 or more repeated (lll, 444, MMm, ###)
const input = "Dfdf123125";
const myStr = input.toLowerCase();
const n = 3;
let isRepeating = false;
let isSequential = false;
for (let i = 0; i < myStr.length; i++) {
if (i + (n - 1) <= myStr.length) {
let isRepeatingTemp = false;
let isSequentialTemp = false;
for (let j = i; j < i + n; j++) {
(myStr.charCodeAt(i) === myStr.charCodeAt(j)) ? isRepeatingTemp = true: isRepeatingTemp = false;
(myStr.charCodeAt(i) === myStr.charCodeAt(j) - (n - 1)) ? isSequentialTemp = true : isSequentialTemp = false;
}
if (isRepeatingTemp) isRepeating = true;
if (isSequentialTemp) isSequential = true;
}
}
Im trying to to see if I can optimize this and make it more readable with underscore and/or even make time/space complexity better. I know this can also be done with regx but im trying to get it done without it.
Instead of the inner for loop, I chunked the string to n using Array.prototype.slice() to see ahead n characters. I used Array.prototype.indexOf() to find if it's sequential based off the abc and num constants(ref). To see if it's repeating, I used Array.prototype.every() that loops through the chunk and check if they're similar and return a boolean based on the expression.
The result gives the output of each instance found, and if it was sequential or repeating.
const input = "Dfdf123125";
function RepSeq(str, n) {
var rep = false;
var seq = false;
var result = [];
const num = '0123456789';
const abc = 'abcdefghijklmnopqrstuvqxyz';
if (str.length < n) return false;
for (var i = 0; i < str.length; i++) {
if (i + n > str.length) break;
var chunk = str.slice(i, i + n);
var seqABC = abc.indexOf(chunk) > -1;
var seq123 = num.indexOf(chunk) > -1;
if (seq123 || seqABC) {
seq = true;
result.push(chunk);
}
if ([...chunk].every(v => v.toLowerCase() === chunk[0].toLowerCase())) {
rep = true;
result.push(chunk);
}
}
return {
repetition: rep,
sequential: seq,
out: result
};
}
console.log(RepSeq(input, 3));
// Output:
// {
// out: ["123"],
// repetition: false,
// sequential: true
// }
With this method, we're peeking at the string one block(i+n) at a time. Ex(n=3):
1. [Dfd]f123125
2. D[fdf]123125
3. Df[df1]23125
4. Dfd[f12]3125
5. Dfdf[123]125 - Sequential!
6. Dfdf1[231]25
7. Dfdf12[312]5
8. Dfdf123[125]

Js function that returns a matching letter from 2 strings

Function that returns the first letter that is present in both strings that a user submits via
an input type text, the strings are separated with a comma. For example:aaaaa,bbbbba--> the matching letter is 'a'because is present in both strings
Sorry for some italian names but i code in italian
I'm not sure how to continue, i have a for to go throught both strings, but i'm not sure if it's correct
function Ripetizione() {
var rip = document.getElementById("string").value;
if (rip.indexOf(",") == -1) { //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma
for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string
}
for (k = 0; i <= stringa2.lenght; k++) { //same for the string2
}
}
Ripetizione()
You need not loop the second string.. Just check for index of the element => 0 , while looping through each element of first string part. And return the value..
Always prefer functional over imperative programming.Use Array#find
function getCommonLetter(str){
const [stringA, stringB]=str.split(',');
return Array.from(stringB).find(val => stringA.includes(val));
}
console.log(getCommonLetter('ab,ba'))
console.log(getCommonLetter('ads,bsd'))
console.log(getCommonLetter('aaa,bbc'))
function Ripetizione() {
var rip=document.getElementById("string").value;
if (rip.indexOf(",")==-1){
alert("Non c'è nessuna virgola");
return;
}
var stringa1=rip.substr(0,rip.indexOf(","));
var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));
return search(stringa1, stringa2);
}
function search(a, b){
for(var i=0; i<a.length;i++){
for(var j=0;j<b.length;j++){
if(a[i] == b[j]){
return a[i];
}
}
}
}
We can do it using Array#reduce and check for the presence of the matching chars using Array#includes.
The idea is to convert the strings into an array of string using Array#from then use the reduce function to match and accumulate the matched characters.
//returns the matching chars as an array
function Ripetizione(rip) {
//let rip=document.getElementById("string").value;
let strs = rip.split(",");
if (strs.length !== 2){ //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
//converting strings to array to use reduce
let strOne = Array.from(strs[0]), strTwo = strs[1];
return strOne.reduce((acc,alpha)=> {
return !acc.includes(alpha) && strTwo.includes(alpha)?[alpha,...acc]:acc;
},[]).slice(0,1).toString();
}
console.log(Ripetizione("aaaaaab,bbbbba"));
console.log(Ripetizione("aaaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbcba"));
console.log(Ripetizione("dddddddd,bbbbba")); //return blank string
console.log(Ripetizione("ab,ba"));
function Ripetizione() {
var rip = document.getElementById("string").value;
if (rip.indexOf(",") == -1) { //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma
if (stringa1.length <= stringa2.length) {
stringa2 = stringa2.split('')
stringa1 = stringa1.split('')
for (i = 0; i <= stringa2.length; i++) { //for cycle to count the elements of the first string
if (stringa1.includes(stringa2[i])) {
console.log(stringa2[i]);
}
}
} else if (stringa1.length >= stringa2.length) {
stringa1 = stringa1.split('')
stringa2 = stringa2.split('')
for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string
if (stringa2.includes(stringa1[i])) {
console.log(stringa1[i]);
}
}
}
}
<input id="string" type="text">
|<button id="ok" onclick="Ripetizione()">done</button>
The following demo binds the change event to input. When a user enters text in input then clicks outside of input the function is called. The function uses split() and filter() and displays the result in an output. The function also removes any spaces and reports if there are no matches as well.
Demo
Details are commented in demo
var str = document.getElementById("string");
// This is an Event Handler
function ripZ(e) {
var result = document.getElementById('result');
var rip = this.value;
if (rip.indexOf(",") === -1) {
result.value = "Separate the two strings with a comma (no spaces).";
return;
}
// If there's a space remove it
var rip = rip.replace(/\s/g, '');
// Split the string at the comma making an array of two strings
var array = rip.split(',');
/*
Take each string and split them at each letter.
Now there's two arrays of letters
*/
var first = array[0].split('');
var second = array[1].split('');
/*
Loop through both arrays by using two for...of loops
*/
var match = first.filter(function(f, i) {
return second.indexOf(f) !== -1;
});
// Display results
if (match) {
result.innerHTML = `
The letter "${match[0]}" is the first match between both strings.`;
} else {
result.value = "There was no match."
}
return;
}
/*
This is an onevent property registered to the input
If a user types into the input then clicks outside of input
the Event Handler ripZ() is called.
*/
str.onchange = ripZ;
<input id='string'><button>GO</button><br>
<output id='result'></output>
If the input was "ab,ba", you sad that it should be return b so Code must be above in my openion :
function Ripetizione() {
// var rip=document.getElementById("string").value;
// if (rip.indexOf(",")==-1){
// alert("Non c'è nessuna virgola");
// return;
// }
// var stringa1=rip.substr(0,rip.indexOf(","));
// var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));
var stringa1="ab";
var stringa2="ba";
for(var i=0; i<stringa2.length;i++){
for(var j=0;j<stringa1.length;j++){
if(stringa2.charAt(i) === stringa1.charAt(j)){
console.log(stringa2.charAt(i));
return;
}
}
}

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'));

Categories

Resources