I have this function which decrypts encrypted message. First letter in the encrypted text is a signal character.
function decryptWord(cipherText, indexCharacter, plainAlphabet, cipherAlphabet)
{
var signalCharacter = cipherText.charAt(0);
var decryptedString;
cipherAlphabet = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 1; count<cipherText.length; count++)
{
var singleLetter = cipherText.charAt(count);
var i = cipherAlphabet.indexOf(singleLetter);
decryptedString = decryptedString + plainAlphabet[i];
}
return decryptedString;
}
I'm looking for word JAVASCRIPT as a result but i get 'undefinedJAVASCRIPT' is that because when the first loop is being carried out there is no value assigned to decryptedString? is there a way to go around it? Thanks.
Exactly right, try initialising decryptedString to "".
Related
Let's say I have a string as such:
var text = "Hi 😂😂";
I want to store this text in a database and wish to convert the emoji's to unicode.
My current solution is to convert the string to an array. Then convert each character to unicode.
function toUnicode(text){
var arr = Array.from(text);
var unicodeArr = [];
for (let i = 0; i < arr.length; i++) {
var unicode = arr[i].codePointAt(0).toString(16);
unicodeArr.push(unicode);
}
return JSON.stringify(unicodeArr);
}
Here are the output when I run the code:
var text = "Hi 😂😂";
var unicodeArr = toUnicode(text);
console.log(unicodeArr); //["48","69","20","1f602","1f602"]
The only issue is that I'm not sure how to convert this back to a whole string.
Is there a much more easy solution to store this var text = "Hi 😂😂"; in a Database?
I modified your "toUnicode" function to return an array of numbers and not a jsonified array of number.toString, so I didn't have to parse it all again to unpack it. Give this a try:
function toUnicode(text){
return Array.from(text).map(char => char.codePointAt(0));
}
function fromUnicode(unicode) {
return unicode.map(num => String.fromCodePoint(num)).join("");
}
var text = "Hi 😂😂";
var unicodeArr = toUnicode(text);
var backToString = fromUnicode(unicodeArr);
console.log(text, unicodeArr, backToString);
You can convert to base64 which is platform agnostic:
var text = "Hi 😂😂";
const b64 = btoa(unescape(encodeURIComponent(text)));
const txt = decodeURIComponent(escape(atob(b64)));
console.log(b64);
console.log(txt);
I'm completely stuck here. Here's the problem I'm solving:
A shift cipher takes a plain text message and shifts each letter forward in the alphabet by a given number. For example, a shift cipher with a shift of 1 would turn the string 'hello' to 'ifmmp'.
Example:
const cipher = new ShiftCipher(2);
cipher.encrypt('I love to code!'); // returns 'K NQXG VQ EQFG!'
cipher.decrypt('K <3 OA RWRRA'); // returns 'i <3 my puppy'
Here's my code:
// Write class below
class ShiftCipher {
constructor(num) {
this.num = num;
}
encrypt(str) {
const lowCase = str.toLowerCase();
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let encrypted = '';
for(let i = 0; i < lowCase.length; i++) {
if(!alphabet.includes(lowCase[i])) {
encrypted += lowCase[i];
}
for(let j = 0; j < alphabet.length; j++) {
if(lowCase[i] == alphabet[j]) {
encrypted += alphabet[j + this.num].toUpperCase();
}
}
}
console.log(encrypted);
}
}
const cipher = new ShiftCipher(2);
cipher.encrypt('I love to codez!');
Last two lines is for testing my method. Everything works fine until iteration doesn't come to an end of alphabet. I added z to the end to test it working with last letter of alphabet. It should start over from alphabet so when I call Z with 2 it should return B but of course I get error because string ends and I'm unable to make it start over.
I've googled around and understand that continue might be solution here but I have still failed to use it in my code.
Cheers!
The problem seems to be this line:
encrypted += alphabet[j + this.num].toUpperCase();
When you reach the end of the alphabet, the letter z, j + this.num will be greater than the length of the alphabet. Indexing the array out of range will produce undefined so your code breaks.
Add a wrap-around like this:
encrypted += alphabet[(j + this.num) % alphabet.length].toUpperCase();
Unable to split same string for two times.What i am doing wrong?
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = ary.split(',');
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
//alert(myarray[i]);
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true);
$('.batch_ed').multiselect('rebuild');
}
Finally returning original string!!
Need to get text before-and split text separated by ,
need to get left and right only as array
Edit: adding the code snippet posted in the comment.
var elements = "";
var batchnoe= "";
$.each(data.response.frc_disloc, function (a,b){
batchnoe = '.batch_ed';
$(batchnoe).each(function(i, obj) {
var batch_splt = b.frac_side;
var myarray = batch_splt.split(',');
for(var i = 0; i < myarray.length; i++) {
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true); $('.batch_ed').multiselect('rebuild');
}
});
});
please check console logs for the output.
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = myarrays.split(',');
console.log(splt);
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
console.log(splt[i]);
$(this).find("option[value ='"+splt[i]+"']").attr("selected",true);
//$('.batch_ed').multiselect('rebuild');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="disc_comm_tlside_ed"></div>
I'm trying to write a script that adds the left side of a string and validates it against the right side.
For example:
var left = "12345"
var right = "34567"
I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7.
I just don't have a clue how to do it.
I think I need to use a for loop to iterate through the numbers such as
for (var i = 0, length = left.length; i < length; i++)
But I'm not sure how to add each number from there.
EDIT the var is actually being pulled in from a field. so var left = document.blah.blah
DEMO
var left = "12345"
var right = "12345"
function add(string) {
string = string.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
return sum; //return when done
}
alert(add(left) === add(right));​
Find the length of the string
then in a temp Variable store the value pow(10,length-1)
if you apply module function (left%temp) you will ge the Last significant digit
you can use this digit to add
repeat the process till the length of the string left is 0
6 Repeat all the steps above for the right as well and then compare the values
Note: convert the string to int using parseInt function
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
stringSum(a) == stringSum(b)
I have a function which has to change characters from one array to the characters from another. It is kind of simple encryption. I have:
var plainArray = ['A','B','C',...,'Z'];
var cipherArray = ['a','b','c',...,'z'];
function rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)
already working.
Now I have to write a function which will change given word into encrypted word.
function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)
{
var encryptedString = signalCharacter;
//i is what will hold the results of the encrpytion until it can be appended to encryptedString
var i;
// rotate array to signal character position
var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 0; count < plainText.length; count++)
{
plainAlphabet = plainText.charAt(count);
i = cipherAlphabet[plainAlphabet];
encryptedString = encryptedString + rotateArray[i];
}
return encryptedString;
}
This function returns signal character and then a string of errors. Do you know what is wrong?
You are overwriting plainAlphabet with one character, thus discarding the alphabet. I guess that's not what you want.
However, you only posted the signature of rotateToPosition and not the actual code of it, so I cannot test my solution.
function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet) {
var encryptedString = signalCharacter;
//i is what will hold the results of the encrpytion until it can be appended to encryptedString
var i;
// rotate array to signal character position
var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 0; count < plainText.length; count++)
{
var plainLetter = plainText.charAt(count);
i = cipherAlphabet[plainLetter];
encryptedString = encryptedString + rotateArray[i];
}
return encryptedString;
}