user2037445
user2037445

Reputation: 161

Encoding of every characte in Url including - _ . ! ~ * ' ( ) in javascript

I used encodeURIComponent() method to encode the url in javascript..by using that method also some characters arent getting encoded..Could anyone suggest a method or code that encodes each and every character in the Url including
- _ . ! ~ * ' ( ).Thank you.

Upvotes: 0

Views: 69

Answers (2)

RobG
RobG

Reputation: 147483

You can write your own encode and decode functions:

function encodeString(s) {
  var result = [];
  for (var i=0, iLen=s.length; i<iLen; i++) {
    result.push('%' + s.charCodeAt(i));
  }
  return result.join('');
}

function decodeString(s) {
  s = s.split('%');
  result = [];

  for (var i=0, iLen=s.length; i<iLen; i++) {
    result.push(String.fromCharCode(s[i]));
  }
  return result.join('');
}

var s = "- _ . ! ~ * ' ( )";

alert(encodeString(s)); // %45%32%95%32%46%32%33%32%126%32%42%32%39%32%40%32%41

alert(decodeString(encodeString(s))); // - _ . ! ~ * ' ( )

Edit

The above seems to encode in base 10, whereas encodeURIComponent seems to encode in base 16, so here's an alternative that uses base 16 (hex):

function encodeString(s) {
  var result = [];
  for (var i=0, iLen=s.length; i<iLen; i++) {
    result.push('%' + s.charCodeAt(i).toString(16));
  }
  return result.join('');
}

function decodeString(s) {
  s = s.split('%');
  result = [];

  for (var i=0, iLen=s.length; i<iLen; i++) {
    result.push(String.fromCharCode(parseInt(s[i], 16)));
  }
  return result.join('');
}

alert(encodeString(s)); // %2d%20%5f%20%2e%20%21%20%7e%20%2a%20%27%20%28%20%29

The first wasn't decoding properly in IE 8, I didn't have time to fix it and don't have IE available right now. You may need to feature test to see which radix to use for decoding.

Upvotes: 1

Pointy
Pointy

Reputation: 413916

The encodeURIComponent method should only be used on "pieces" (components) of the URL. It's for putting together the query string or the path when you're constructing the URL from user-supplied or computed fragments.

There really can't be a general "encode my URL properly" method, because it can't tell what parts of the URL you do and don't want to encode. Instead, use encodeURIComponent() on the pieces of the URL that you're putting together before you add them to the final string.

Upvotes: 0

Related Questions