I get a NaN error when converting with charCodeAt [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How can i fix this issue where the alerted Encrypted value is NaN?
function Encrypt() {
var Plaintext = document.getElementById("txt").value;
var Key = Math.floor(Math.random() * 26) + 1;
var Chaesarshifted = caesarShift(Plaintext,Key);//i just didn't paste Chaesarshift code
var Encrypted;
alert(Chaesarshifted);
for (let index = 0; index < Chaesarshifted.length; index++) {
Chaesarshifted.toLowerCase();
//till here everything works fine
Encrypted += Chaesarshifted.charCodeAt(index) - 96;
}
alert(Encrypted);// Alert says NaN
}

The initial value of Encrypted is not set. So when you are trying to += to it, it doesn't know how to handle that operation.
You should prime Encrypted to the empty string "" for the starting value.
Then, inside the for loop, Chaesarshifted.toLowerCase(); does not set the value, but must be stored.
Also, your logic is off to append the Encrypted text. You need to change the character back into a unicode character. Or possibly even build an array to concatenate later.
Finally, you should start your variable names with a lowercase to follow convention.
To put it all together:
function Encrypt() {
var plaintext = document.getElementById("txt").value;
var key = Math.floor(Math.random() * 26) + 1;
var chaesarshifted = caesarShift(plaintext,Key); //missing chaesarshift code
var encrypted = "";
alert(chaesarshifted);
chaesarshifted = chaesarshifted.toLowerCase();
for (let index = 0; index < chaesarshifted.length; index++) {
//missing code
encrypted += String.fromCharCode(chaesarshifted.charCodeAt(index) - 96);
}
alert(encrypted);// Alert will show garbled text (offset values from chaesarshift str)
}
Edit: Thanks to Barmar's comment to get me thinking about the problem more.

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
}

Why Random variable is only returning 1 character [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Hey guys im trying to generate a random password using upper and lowercase keys + numbers. the code seems to work but instead of returning 20 characters its instead returning only 1. The return seems random.
The element should be replaced why the random password every time the button is clicked.
HTML
<button id = "button5" onclick = "password()">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
This is the Javascript
function password (length ) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; <length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
return ranpassword;
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
console.log(password(20));
}
whenver the button is clicked, one random letter is returned in console.log and i cant seem to understand why ? Can anyone tell me why?
Any help would be great . Thanks :)
You did some mistake. Try this code,
function password (length) {
let ranpassword = "",
chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ",
charalength = chara.length;
for (var i = 0; i<length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick="password(20)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
Aside from your password function implementation partly wrong, you are not passing a length to password() function in your onclick handler.
You need to pass the length as well like password(20):
<button id = "button5" onclick = "password(20)">Generate password </button>
as #Locke said, your for loop syntax is incorrect, as You are missing i in the comparison. Other than that, you code is flooded with typos. You didn't close the for loop, and you didn't need to return ranpassword. Now your code works, notice that the number I put as a parameter in the onclick in the HTML is the length your password will be. Also, instead of using .chatAt, I generate a random number and add it to ranpassword. For example: The for loop gets chara[4], so randpassword has chara's 5th letter.
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; i < length; i++) {
ranpassword += chara[(Math.floor(Math.random() *
chara.length))];
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick = "password(4)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
I have fixed the problem
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charalength = chara.length;
for (var i = 0; i < length; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() * chara.length));
}
return ranpassword;
}
console.log(password(5));
you were returning the password form the loop so it was returning a single character

Javascript - Online Coding assessment to mask credit cards numbers with # [duplicate]

This question already has answers here:
Masking credit card number
(5 answers)
Closed 12 months ago.
I got the below coding assessment question in Javascript. I tried my best to solve but there are few edge cases I missed. I need help to identify those missing cases
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct.
However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
This is what I tried so far
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
if (i < 4) {
newString += reversed[i];
} else {
newString += '#';
}
}
return reverse(newString);
Output
This is my solution:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar + cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
I ran it with all the numbers of your example and it gets the correct output.

how to do encryption with "java script" and decryption with and "java" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to encrypt the "url" in java script by using below method
var s='';
for(var i=0;i<origUrl.length;i++)
{
var c=origUrl.charCodeAt(i);
if(c != ' ')
{
c=String.fromCharCode(c + 47);
if( c > '~')
{
c=String.fromCharCode(c - 94);
}
}
s=s.concat(c);
}
and for decryption in java I am using below code
public static String rotate(String value)
{
int length = value.length();
String result = "";
for (int i = 0; i < length; i++)
{
char c = value.charAt(i);
// Process letters, numbers, and symbols -- ignore spaces.
if (c != ' ')
{
c += 47;
if (c > '~')
c -= 94;
}
result=result+c;
}
return result.toString();
}
Both code has same logic but it is not working for me, means when I am passing java script generated string to server side and doing decryption, I am not getting the correct string which I am expecting.
on other hand if I am executing this logic in java standalone application then it is working for me.
Please check below
String url = "https://abcd.com";
System.out.println(url);
String encode = rotate(url);
System.out.println(encode);
String decode = rotate(encode);
System.out.println(decode);
and output
https://abcd.com
9EEADi^^2345]4#>
https://abcd.com
your javascript code is incorrect....
i am getting the garbage value...
<script>
function getval(origUrl){
///from here
var s='';
for(var i=0;i<origUrl.length;i++)
{
var j=origUrl.charCodeAt(i); // here in you are storing integer in j.
var k='';
if(j != ' ') // don't compare " " with j because j contains integer
{
k=String.fromCharCode(j + 47);
if( j > '~') // here too j contains integer...
///you cann use String.fromCharCode(j); that is ok
{
k=String.fromCharCode(c - 94); //where the variable c is declared???
}
}
s=s.concat(k);
}
// upto here source code is same...as you provided...
return s;
}
var text="https://abcd.com";
alert(text);
alert(getval(text));
alert(getval(getval(text)));
</script>
There are two problems in your JavaScript code, both of which are in the innermost if block.
if( j > '~')
{
k=String.fromCharCode(c - 94);
}
First off, you are checking if j is bigger than '~'. That's almost what you want. Since j isn't the variable that's actually changing here, you should instead be checking if k > '~'.
Second, you have a variable called c inside that if block that doesn't exist anywhere else. I am guessing you copied and pasted from the Java to the Javascript and forgot to rename that variable. Again, what you need it to be is k. Additionally, because k is a string, you need to get the charCode from it.
With these problems in mind, that if block should become this:
if (k > '~')
{
k = String.fromCharCode(k.charCodeAt(0) - 94);
}
function rotate(x)
{
var s=[];
for(var i=0;i<x.length;i++)
{
var j=x.charCodeAt(i);
if((j>=33)&&(j<=126))
{
s[i]=String.fromCharCode(33+((j+14)%94));
}
else
{
s[i]=String.fromCharCode(j);
}
}
return s.join('');
}

Javascript Numbers and Comma with input pattern [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I need to combine 2 error checking procedures. I dont use jquery
I only want these values appear 0123456789,
My HTML, i need to know the pattern for other instances of my website
<input type="text" pattern="?" maxlength="10" id="f2f11c3" value="0"></input>
My JS
document.getElementById("f2f11c3").addEventListener("keyup", function(){addcommas("f2f11c3")}, false);
.
function addcommas(id)
{
//i dont know what to place here
//every 3 numbers must have a comma
//ie. input is 123.c39,1mc
//it must also remove if a comma is placed manually
//result must be 123,391
}
Hope someone could help. Thanks!
document.getElementById('f2f11c3').
addEventListener("input", function(){addcommas();}, false);
function addcommas()
{
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/\D/g, '');
var i,temp='';
for(i=t.length; i>=0;i-=3){
if(i==t.length) {
temp=t.substring(i-3,i);
}
else
{
if(t.substring(i-3,i)!="")
temp = t.substring(i-3,i)+','+temp;
}
if(i<0) {temp=t.substring(0,i+3)+','+temp; break;}
}
v.value = temp;
}
DEMO
function addcommas(id) {
var arr = [];
// loop over the id pushing numbers into the array
for (var i = 0, l = id.length; i < l; i++) {
if (id[i] >= 0 && id[i] <= 9) {
arr.push(id[i]);
}
}
// loop over the array splicing in commas at every 3rd position
for (var i = 0, l = arr.length; i < l; i += 3) {
arr.splice(i, 0, ',');
i++;
l++;
}
// remove the first unnecessary comma
arr.shift()
// return the comma-separated string
return arr.join('');
}
DEMO
The id is an HTML element's id, not the value
function addcommas(id)
{
//Not really needed, but just to shorten the details below
var x = document.getElementById(id);
//Current value but removes anything aside from numbers 0-9 and comma (not really needed)
var curval = x.value.replace(/[^\d,]/g,'');
//Strips the comma from the current value if someone entered it manually.
var nocomma = x.value.replace(/[^\d]/g,'');
//If not blank, prevent NAN error
if (nocomma.length>0)
{
//Converts text to int
nocomma = parseInt(nocomma, 10);
//Dont know why, but doesnt work without this
nocomma = nocomma+0;
//Converts it back to string to add the comma
nocomma = nocomma+"";
//Adds comma every 3 numbers, I got this from other research, dont know how it works
x.value = nocomma.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
}
My Input in the HTML is as follows
//for iphone, this will popout the numberpad with choices 0-9 only. Easier to type, better mobile usability.
<input type="text" pattern="\d*" maxlength="12" id="f2f11c3" value="0"></input>

Categories

Resources