JavaScript Tricks; URLEncode, Foreach and Remove last character

I have come across some neat (if not mind blowing) tricks with JavaScript recently.

Firstly, I needed JavaScript code that copied PHP’s urlencode().
This function returns an encoded string where all non-alphanumeric characters except – _ . are replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

JavaScript has 2 functions to emulate urlencode(), but both fall short…
The escape function encodes all non-alphanumeric characters except * @ / + – _ .
The encodeURIComponent function encodes all non-alphanumeric characters except spaces and ! ‘ ( ) * ~

The winner for me though is encodeURIComponent as it encodes all UTF-8 characters while escape only encodes ISO Latin characters.

With this in hand, mozilla help provide a neat function.

function url_encode( s ) {
	return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );

This basically uses regular expressions to do a global replace on characters encodeURIComponent misses.

Another tiny trick that I liked is a JavaScript foreach loop. I use this regularly in PHP but its not exactly obvious in JavaScript.
Use the following code…

var some_array = new Array;
some_array['a'] = 1;
some_array['b'] = 2;
some_array['c'] = 3;
for ( var key in some_array ) {
  var value = some_array[key];
  console.log( 'Key: ' + key + ', Value: ' + value ); 
// Key: a, Value: 1
// Key: b, Value: 2
// Key: c, Value: 3

This is particularly handy with associative arrays like above.

Final ickle trick is a bit of code to remove the last character from a string. Use the JavaScript slice function and its easy peasy…

var some_string = '"102","123","45","583",';
some_string = some_string.slice(0, -1);

Why is this handy? Well I use loops to construct formatted stings with some delimiter, like the comma in the code above.
However the string usually ends up with the delimiter added on at the end. So I like to remove it at the end rather than checking if I should not append the delimiter with each iteration of the loop.
I think it is much tidier and it is probably quicker but I am open to correction.

2 thoughts on “JavaScript Tricks; URLEncode, Foreach and Remove last character

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s