Escape & Unescape – Deprecated?

 


Two of the most widely used JavaScript functions that are now deprecated are the escape() and unescape() functions. This means that in order to ensure that your code will continue to work in all future browsers, you should use one of the alternative functions as was indicated on MDN:

  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()

What To Do When They Are No More

Since these functions may not always exist, I decided to write the necessary JavaScript code to make sure they can continue to be used:

(function() {
var objGlobal = this;
if(!(objGlobal.escape && objGlobal.unescape)) {
  var escapeHash = {
    _ : function(input) {
      var ret = escapeHash[input];
      if(!ret) {
        if(input.length - 1) {
          ret = String.fromCharCode(input.substring(input.length - 3 ? 2 : 1));
        }
        else {
          var code = input.charCodeAt(0);
          ret = code < 256
            ? "%" + (0 + code.toString(16)).slice(-2).toUpperCase()
            : "%u" + ("000" + code.toString(16)).slice(-4).toUpperCase();
        }
        escapeHash[ret] = input;
        escapeHash[input] = ret;
      }
      return ret;
    }
  };
  objGlobal.escape = objGlobal.escape || function(str) {
    return str.replace(/[^\w @\*\-\+\.\/]/g, function(aChar) {
      return escapeHash._(aChar);
    });
  };
  objGlobal.unescape = objGlobal.unescape || function(str) {
    return str.replace(/%(u[\da-f]{4}|[\da-f]{2})/gi, function(seq) {
      return escapeHash._(seq);
    });
  };
}
})();

Reference

I created these functions based on information found at DevGuru.com.

 

7 thoughts on “Escape & Unescape – Deprecated?”

  1. error in line
    ret = String.fromCharCode(input.substring(input.length – 3 ? 2 : 1));

    need to be
    ret = String.fromCharCode(parseInt(input.substring(input.length – 3 ? 2 : 1),16));

  2. The escape and unescape functions are used to send and retrieve AJAX methods flexibly. The methods solve my problem with AJAX call from scripting. I am asking why we need to deprecated them?

  3. Thanks for sharing this useful fallback! I need escape in a project where the server expects ISO-8859-1 encoded URIs, and I don’t have power to change this.

    A tiny improvement: escape and unescape works even if the input is not a string (typically, passing a number), but your functions break since numbers don’t have the replace method.

    Changing line 24 and 29 to:

    return str.toString().replace [...]

    fixes this.

Leave a Reply

Your email address will not be published. Required fields are marked *


nine − 7 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">