String to URI Encoder

JerseyFoo

1/g = g-1
Reaction score
40
I managed to make a ASCII to URI-safe ( Alphanumber + encoder in JavaScript and thought I'd share.

Code:
function baseEncode(s, m){
	var x, asc, alp, cha = 0, val, powc, powv, i, res = '', l = s.length-1;
	asc = (m ? [0, 26, 36, 62, 64, 89, 96, 102, 256] : [33, 46, 48, 58, 65, 91, 97, 123, 256] );
	alp = (m ? [97, 48, 65, 46, 33, 91, 97, 123, -1] : [64, 62, 26, 89, 36, 96, 0, 102, -1] );
	powc = (m ? 32 : 128 );
	for ( i = 0; (val = s.charCodeAt(i)); i++ ){
		powv = (m ? 128 : 32 );
		if ( !m ){ // c2n
			for ( x=1; val>=asc[x]; x++ ){}
			val -= asc[x-1] - alp[x-1];
		}
		while( powv > 0 ){
			//if (( cha + powc ) >= basec ){
			if ( val >= powv ){
				val &= ~powv;
				cha |= powc;
			}
			powc >>= 1;
			powv >>= 1;
			if ( powc === 0 || (powv === 0 && i === l && powc !== 1) ){
				if ( m ){ // n2c
					for ( x=1; cha>=asc[x]; x++ ){}
					cha -= asc[x-1] - alp[x-1];
				}
				res += String.fromCharCode(cha);
				cha = 0;
				powc = (m ? 32 : 128);
			}
		}
	}
	return res;
}

Example Usage
Code:
s = '++==233322abcdg!@#$%^&*()@#';
alert(s);
s = baseEncode(s, true);
alert(s);
s = baseEncode(s, false);
alert(s);
Alerts...
  • ++==233322abcdg!@#$%^&*()@#
  • kOIZptiPmPmOmCf8ySrDiua9jcv4j8EEkua9
  • ++==233322abcdg!@#$%^&*()@#

Intended for an AJAX Chat, next up is compression. ( character-sequenced probability t > h > a/i )

Comments welcome.

ALSO: I'm using the '.' and '/' for the extra 2 characters aside from alphanumericals ( 62 + 2 ), is that safe. Would ":" and ";" be safer?
 

TFlan

I could change this in my User CP.
Reaction score
64
Why not use escape() or encodeURIComponent()
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top