String to Hex and Back for location # hash Url use

Just a quick one.

While sending out my Hype designed Christmas Card to people, I was relying on using the location hash to enter the recipients names and code for choice of greating.

No real issue with that but one thing that bothered me was before the recipients clicked on their link, they would see their names in the url string.
Again not a big deal. But it dawned on me I could use hex conversion.

Also I just hate the look of the URL encoding for spaces etc..

For example my original URL ( not real ) would look like this.

http://markosx.com/foo/card.html#mgzz-lvjj-DJS,%20John,%20Paul%20Grizz%20,Cliff%20&OurMusicRadio%20Listners

The mgzz would be for which of main message and lvjj for which sign off
The rest would be for the who to.
The Hype functions would read this and set up the card on load.

But as I say, I was not really happy with the way this looks.

So now I can run a plain text string through the encoder below

String to Hex code

function ConvertStringToHex(str) {
              var arr = [];
              for (var i = 0; i < str.length; i++) {
                     arr[i] = ( str.charCodeAt(i).toString(16)).slice(-4);
              }
              return  arr.join("");
       }
 

var str = "mgzz-lvjj-DJS John, Paul, Grizz,Cliff & all our listners";
 

var strngToHex =ConvertStringToHex(str) 
 

console.log('string -> hexCode = ' ,strngToHex); 

and use the hexcode in the url

i.e "mgzz-lvjj-DJS John, Paul, Grizz,Cliff & all our listners"

would become
http://markosx.com/foo/card.html#6d677a7a2d6c766a6a2d444a53204a6f686e2c205061756c2c204772697a7a2c436c696666202620616c6c206f7572206c6973746e657273


In the Card Project a Hype function would convert it back a runtime when someone opens their card.

Hex to String

	function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

var hexToString = hex2a('6d677a7a2d6c766a6a2d444a53204a6f686e2c205061756c2c204772697a7a2c436c696666202620616c6c206f7572206c6973746e657273')
console.log('hexCode -> string  =' ,hexToString); // returns '2460'

Oh and Merry Christmas.

3 Likes