Glitch in JavaScript: Converting Text to Numbers

My current challenge involves converting text into numbers using code. Here is the code snippet I have:


var vals= ["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","0","1","2","3","4","5","6","7","8","9"," ",",",".","!","?","/","\\","#","@","=","-","_",":"];
var input = prompt("Input:");
var inn = input.toLowerCase + "";
var ins = inn.split("");
var pswrd = prompt("Password(LowerCase):")
var pin = pswrd.toLowerCase + "";
var pins = pin.split("");
var out = "";
var i;
var mul = Math.floor((Math.random() * 30) + 1);
for(i=0;i<ins.length;i++){
  var num = ins[i]
  var val = vals.indexOf(num)
  var out = out+val*mul+" "
}
var out = out+"ↀ"
for(i=0;i<pins.length;i++){
  var num = pins[i]
  var val = vals.indexOf(num)
  var out = out+val*mul+" "
}
alert('Result:' + out);

Despite my efforts, when I run the code with the input "Hello" and password "hi", I get an unexpected output:

Input: Hello

Password: hi

Output: 50 200 130 20 190 80 140 130 360 190 140 -10 140 220 40 170 -10 0 180 40 -10 -10 360 -10 360 -10 130 0 190 80 210 40 360 20 140 30 40 -10 360 -10 ↀ50 200 130 20 190 80 140 130 360 190 140 -10 140 220 40 170 -10 0 180 40 -10 -10 360 -10 360 -10 130 0 190 80 210 40 360 20 140 30 40 -10 360 -10

I'm in need of help to understand the issue. Any assistance would be greatly appreciated. Thank you!

Answer №1

your approach to coding is subpar, javascript deserves a more elegant solution

const values = 'abcdefghijklmnopqrstuvwxyz0123456789 ,.!?/\\#@=-_:' 

var multiplier = Math.floor((Math.random() * 30) + 1)
  , input = (prompt('Enter Input:')).toLowerCase()
  , password = (prompt('Enter Password (LowerCase):')).toLowerCase()
  ;
var output  = ''

for (let char of input)  
  output += `${ values.indexOf( char ) * multiplier} `;

output += 'ↀ'

for (let char of password)  
  output += `${ values.indexOf( char ) * multiplier} `;

alert('Output: ' + output)

Answer №2

Using the toLowerCase method is necessary instead of treating it like a property of the object. It seems you were encountering errors due to concatenating an empty string, which may have masked the issue without actually resolving it.

Additionally, consider chaining multiple methods instead of creating new variables for every data mutation step. It's also worth questioning the need for calling indexOf within the loop when the current index is already stored in i.

While I won't refactor the entire code block for you, you can give this a try:

var vals= ["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","0","1","2","3","4","5","6","7","8","9"," ",".","!","?","/","\\","#","@","=","-","_",":"];
var input = prompt("Input:");
var pswrd = prompt("Password(LowerCase):")
var inn = input.toLowerCase().split("");
var pin = pswrd.toLowerCase().split("");
var out = "";
var i;
var mul = Math.floor((Math.random() * 30) + 1);
for(i=0;i<inn.length;i++){
  var num = inn[i]
  var val = vals.indexOf(num)
  var out = out+val*mul+" "
}
var out = out+"ↀ";
for(i=0;i<pin.length;i++){
  var num = pin[i]
  var val = vals.indexOf(num)
  var out = out+val*mul+" "
}
alert('Result:' + out);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQUERY confirm dialog causing AJAX malfunction

I am encountering an issue where I am trying to execute an ajax function only after the user confirms a dialogue using JQUERY confirm. Strangely, when I include the confirmation step, my code throws an error and does not function properly. It's worth ...

Breaking down a URL based on one of two distinct components

Currently, I have a piece of code that splits the URL and removes everything after &7. Is there a way to modify it so that it also checks for |relevance simultaneously and splits based on whichever one is found? $(document).ready(($) => { const pa ...

Connect jQuery's resizable controls

Check out this jSFiddle. I am attempting to add event handlers for resizing $('oWrapper_'+num). However, the resizing does not occur. This is because $('#oWrapper_'+num) has not been added to the dom at the time of execution, so the se ...

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

Is it sufficient to only capture 4xx errors?

Is it necessary to catch both 4xx and 5xx errors, or is catching just 4xx errors sufficient? In regular testing of my code, when would a 5xx error even occur? ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Angular front-end rendering with Rails backend integration

Currently, I am working on a medium-sized Rails application and my latest endeavor is to integrate Angular into the system. After reviewing several tutorials, it appears that the most common method for fetching initial data and displaying the first view in ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Duo and reference loop

I'm trying to learn how to use backreferences in JavaScript. I have an array and want to replace it within a string. Here's what I've attempted so far: var items = ["book", "table"]; var sentence = "The $1 is on the $2"; var newSentence ...

``How can I easily navigate to the top of the page when changing routes in React Router DOM v6?

What is the best way to scroll to the top when a route changes in react router dom v6? In the past, I used a solution from this StackOverflow post to make my page automatically scroll to the top every time a route changed with react-router-dom v5. However ...

Replace the icon in Material UI Stepper for steps that have errors

I am utilizing Material UI's Stepper component to display a checklist in this manner. The image below is from their documentation. https://i.sstatic.net/KfUos.png While attempting to add an error state to the checklist, I discovered a prop called er ...

Updating the configuration settings for CKEditor 5 using Reactjs

I followed the configuration provided in another answer at But, I am facing an issue: Failed to compile. ./src/components/cards/CreateCard.js Line 59:22: Parsing error: Unexpected token, expected "}" 57 | editor={ClassicEditor} 58 | ...

Is there a way to dynamically pass values to a form in React?

Learning React on my own has been challenging, especially when trying to accomplish what I thought would be a simple task. To put it briefly, I have a menu with several items. I aim to select a menu item and have a form open next to it. The form shoul ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

Identify and click on the child span within the li element using Cypress

I am struggling to select a li element and click/check on the span with the checkbox class, but I can't seem to make it work. Here is what I have attempted: <div id="list-widget"> <ul class="tree"> <li class ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

JavaScript encoding and decoding challenges

Can anyone help me figure out what's wrong? I'm trying to encode and decode a simple input, but it just doesn't seem to work! Any ideas why? Thanks in advance for your assistance :) ENCODE: function encryption_encode(s, delta) { var te ...

Javascript involved in the process of CSS Background-Images loading after HTML Images

I quickly put together a microsite that is located at . If your internet connection isn't fast or nothing is cached, you may notice that the background-images used for CSS image-text replacement are the last items to load (especially the h1#head with ...

Using Python to interact with forms and click JavaScript buttons

Is there a way to automate form filling on a website by setting specific parameters that will bring up products matching those parameters? I attempted to use mechanize in python, but it does not support javascript. It seems like the process of entering par ...