Javascript URLEncode

Let us take a look at what would be the best approach for Encoding URL using Javascript. There are basically 3 Javascript URLEncode methods available.

Types of Javascript URLEncode

  • escape() will not encode: @*/+  :- This method is obsolete and deprecated since ECMAScript v3.  Hence do not use this approach to encoding the URL’s.
  • encodeURI() will not encode: ~!@#$&*()=:/,;?+’  : – If you need to encode the URL completely then you should use encodeURII() method. Below is the example of how to use encodeuri method
    var encodedString=encodeURI("http://www.askmein.com/my page url goes here.html");
    console.log(encodedString);
    
    //This would result below output when we use console log
    //http://www.askmein.com/my%20page%20url%20goes%20here.html
  • encodeURIComponent() will not encode: ~!*()’ :- encodeURIComponent method should be used only to encode the URL parameters/ query string values. Do not encode the actual URL using this method doing so will destroy the URL. Let us take an example of how to use an encodeURIComponent method.
    var world = "A string with symbols / characters that have special meaning?";
    var uri = 'http://askmein.com/foo?hello=' + encodeURIComponent(world);
    console.log(uri);
    
    //The output would result in encoding the query string value only.
    //http://askmein.com/foo?hello=A%20string%20with%20symbols%20%2F%20characters%20that%20have%20special%20meaning%3F
    
    //Note: If we use encodeURIComponent('http://askmein.com/test.html');
    // Output would be "http%3A%2F%2Faskmein.com%2Ftest.html" Hence it is not recommended to use on the URL.
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like