I have 2 strings with some chars. One of them is with "mashed" characters, and the other one is with ordered characters which have some sense. For example:
wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!
Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT
So as you may see - the first one have equivalent of symbols which are the same for the equal symbol in the second one.
And the task is - to create somehow kind of alphabet from them, because I have third one string wich have to be "decoded". (wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!).
And the tricky part here is - that if I'm pretty sure for the first two strings that they're absolutely equal like a number of chars, so about the new one - is completely different number of symbols, but they consisting in the "alphabet"
And here is my current code for creation of the "alphabet":
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
var myenc = {};
var mynewenc = {};
for (i = 0; i < enc.length; i+=1) {
var encoded = new Array(enc[i]);
var decoded = new Array(dec[i]);
myenc[enc[i]] = dec[i];
};
console.log(myenc);
And now - how I have to decode, the new one string, using this "alphabet"?
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
function make_dictionary(enc, dec){
o = new Object();
if(enc.length == dec.length){
for(i=0; i<enc.length; i++){
o[enc[i]] = dec[i];
}
}
else{
console.log('error');
}
return o;
}
function translate(newenc, dictionary, fill){
var newstring = '';
for(i=0; i<newenc.length; i++){
if(typeof dictionary[newenc[i]] !== 'undefined'){
newstring += dictionary[newenc[i]];
}
else{
newstring += fill;
}
}
return newstring;
}
var d = make_dictionary(enc, dec);
console.log(d);
var string = translate(enc, d, '_');
console.log(string);
var string = translate(newenc, d, '_');
console.log(string);
Here's one way that you can approach it (as I understand the question):
// Create your dictionary
var dict = {};
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!".split('');
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT".split('');
// Populate your dictionary
for (var i = 0; i < enc.length; i++) {
dict[enc[i]] = dec[i];
}
// You can use your dictionary like this
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!".split('');
// Returns your translated string
newenc.map(function(e) {
return dict[e];
}).join('');
However for this method you'll have to deal with characters that are defined in newenc that are not defined in your enc (such as T). I tried to do the best I could given the situation and rules that you've described, hope this helps!
If I understand well, you can try using this code.
It is finding the appropriate encoded letter in your enc variable and if the letter is found, it is replacing it with the corresponding letter from your dec variable.
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
for (i = 0; i < newenc.length; i++) {
for (j = 0; j < enc.length; j++) {
if (enc[j] == newenc[i])
newenc[i] = dec[j];
}
};
console.log(newenc);
At the end your variable newenc may contain your decoded string.
Related
I have a string
var str = 'string'
I have a multiplier
var mult = 3
I want to return stringstringstring
The mult will change. Basically mult is kind of like a power but this is a string not a number. And I need to return multiple strings. I'm thinking of looping where mult = the number of times to loop and each would conceptually 'push' but I don't want an array or something like =+ but not a number. I'm thinking I could have the output push to an array the number of times = to mult, and then join the array - but I don't know if join is possible without a delimiter. I'm new at javascript and the below doesn't work but it's what I'm thinking. There's also no ability to input a function in the place I'm running javascript and also no libraries.
var loop = {
var str = 'string'
var arr = [];
var mult = 3;
var i = 0
for (i = 0, mult-1, i++) {
arr.push('string'[i]);
}
}
var finalString = arr.join(''); // I don't know how to get it out of an object first before joining
Not sure if what I want is ridiculous or if it's at all possible
You mean something like below,
var str = 'string'
var mult = 3
var str2 = ''
for(i = 0; i < mult; i++) {
str2 += str
}
console.log(str2)
var str = 'string'
var mult = 3;
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
Using resusable function:
const concatStr= (str, mult)=>{
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
}
concatStr("string",3)
Using the inbuilt Array.from method:
var str = "string"
var mult = 3
var sol = Array.from({length: mult}, ()=> str).join("")
console.log(sol)
function concatString(str, mult) {
var result = ''
for(i = 0; i < mult; i++) {
result = result.concat(str);
}
return result;
}
const value = concatString('string', 3);
console.log(value);
Also you can use array inbuilt methods,
const mult = 3, displayVal = 'str';
Array(mult).fill(displayVal).join('');
// the string object has a repeat method
console.log('string'.repeat(3));
I'm trying to generate a UserID out of userAgent and Date Function. I also wanted to understand callback function (which I still didn't get (JS Noob)). Therefore I built the following example:
var storage = window.localStorage;
var storageUserId = storage.getItem("userID");
var text = "";
function userID(callback){
var agent = window.navigator.userAgent;
var now = new Date();
try{
callback(agent, now);
}catch(e){}
}
function hasher(agent,now){
var hash = 0;
var arr = [];
for(var i = 0; i < arguments.length; i++){
var pars = arguments[i];
for(var j = 0; j < pars.length; j++){
var charI = pars.charCodeAt(j);
hash = ((hash<<5)-hash)+charI;
hash = hash & hash; // Convert to 32bit integer
hash = hash.toString();
}
}
console.log(hash + "|" + hash);
}
userID(hasher);
The result should look like this "9834917834|8293479273" (example numbers to show format). First number hashed agent second number hashed date. I got the hash logic form here: http://mediocredeveloper.com/wp/?p=55
Maybe there is a better way to do this :)
I really appreciate your help!
Thanks a lot!
Best,
Anton
You should extract the hashing loop into a new function:
function hash(str){
var hash = 0;
for(const char of str){
const charCode = char.charCodeAt(0);
hash = ((hash<<5)-hash)+charCode;
}
hash = hash & hash; // Convert to 32bit integer
return hash.toString();
}
So to get the hash you want to you just need to call it twice:
function getUserID(){
return hash(window.navigator.userAgent) + "|" + hash("" + new Date);
}
(PS: you know that new Date will change every millisecond?)
How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}
I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.
How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}