By nickf


2008-12-02 02:37:08 8 Comments

How do you safely encode a URL using JavaScript such that it can be put into a GET string?

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?

15 comments

@Arthur 2019-10-05 20:48:17

Use fixedEncodeURIComponent function to strictly comply with RFC 3986:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

@Adam Fischer 2015-10-01 08:03:26

encodeURIComponent() is the way to go.

var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

BUT you should keep in mind that there are small differences from php version urlencode() and as @CMS mentioned, it will not encode every char. Guys at http://phpjs.org/functions/urlencode/ made js equivalent to phpencode():

function urlencode(str) {
  str = (str + '').toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace('!', '%21')
    .replace('\'', '%27')
    .replace('(', '%28')
    .replace(')', '%29')
    .replace('*', '%2A')
    .replace('%20', '+');
}

@Ryan Taylor 2012-12-15 08:47:32

The best answer is to use encodeURIComponent on values in the query string (and nowhere else).

However, I find that many APIs want to replace " " with "+" so I've had to use the following:

const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.

And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.

Example:

const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

@Jochem Kuijpers 2013-01-20 01:08:13

Please note, you should only replace %20 with + symbols after the first question mark (which is the 'query' part of the URL). Let's say I want to browse to http://somedomain/this dir has spaces/info.php?a=this has also spaces. It should be converted to: http://somedomain/this%20dir%20has%spaces/info.php?a=this%20‌​has%20also%20spaces but many implementations allow '%20' in the querystring to be replaced by '+'. Nevertheless, you cannot replace '%20' with '+' in the path-section of the URL, this will result in a Not Found error unless you have a directory with a + instead of a space.

@Ryan Taylor 2013-07-19 22:16:32

@Jochem Kuijpers, definitely, you wouldn't put "+" in a directory. I'd only apply this to the query parameter values themselves (or keys if needed), not the entire URL, or even the entire query string.

@njzk2 2014-06-02 18:11:51

I would replace in value rather than in the result of the encoding

@Ryan Taylor 2014-06-02 18:17:27

@njzk2 unfortunately encodeURIComponent('+') would give you %2B, so you'd have to use two regular expressions... which I suppose is kinda why this works, because '+' are ' ' are encoded differently in the end.

@xhienne 2019-03-26 12:25:06

There is no reason to translate %20 to "+". The valid escape sequence for ASCII space is %20, not "+" which is not mentioned in RFC 3986 (tools.ietf.org/html/rfc3986). "+" was used in the 1990s; it is obsolete now and is only supported for legacy reasons. Don't use it.

@Ryan Taylor 2019-03-26 15:20:39

@xhienne for sure, it's just something i've noticed in the real world on a few APIs, it would always make more sense to use encodeURIComponent when that works – would be nice if people could stick to one standard! And preferably the RFC spec.

@Gerard ONeill 2019-04-25 20:23:15

Regardless if its a + or a %20, decoding the component should know how to interpret either value and produce a space. It is only specs such as oauth that require encoded strings within its spec where it makes a difference.

@Mohith Maratt 2016-09-27 15:59:49

You can use esapi library and encode your url using the below function. The function ensures that '/' are not lost to encoding while the remainder of the text contents are encoded:

function encodeUrl(url)
{
    String arr[] = url.split("/");
    String encodedUrl = "";
    for(int i = 0; i<arr.length; i++)
    {
        encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
        if(i<arr.length-1) encodedUrl = encodedUrl + "/";
    }
    return url;
}

https://www.owasp.org/index.php/ESAPI_JavaScript_Readme

@Buu Nguyen 2008-12-02 02:43:57

Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

@hitautodestruct 2012-10-28 11:36:53

How about adding the explanation @cms gave? escape is also a valid option.

@Ifnot 2013-03-01 16:35:54

according to @CMS encodeURI is not really safe for URL encoding.

@Buu Nguyen 2013-03-06 19:32:38

@AnaelFavre because it is meant to encode the whole URL, which doesn't allow characters such as :, /, @ etc. These 2 methods are not to be used interchangeable, you must know what you are encoding to use the right method.

@Brad Parks 2016-05-06 13:07:01

As mentioned in another answer on this page, this site nicely details the reason to use this method

@node_saini 2016-10-17 14:31:05

@BuuNguyen this does not work for me. I still see the my & as &amp; in my terminal.

@Venki 2016-12-15 09:23:17

@BuuNguyen : Hi BuuNguyen, thanks for useful solution. can please confirm me ? may I use encodeURIComponent() method for plain string encoding becuase in my application I am appending string content directly as a value to query string key then its leading XSS issue. its my code var mywindow = window .open( "https://" + window.location.host + "center/js/cal.html?context=" + conString + "&amp;date=" + dateString + "&amp;firstName=" + firstName);

@Venki 2016-12-15 09:28:21

@BuuNguyen : Now its saying &amp;firstName could be cause the XSS issue. Now what I have to do ? if I do encode firstname then it will get resolved or not ? please suggest me something. Ty.

@germs12 2017-07-20 22:08:51

There are a lot of good sites out there that will let you play around with this: string-io.com is one.

@jonathana 2019-02-09 10:26:42

Here is a LIVE DEMO of encodeURIComponent() and decodeURIComponent() JS built in functions:

<!DOCTYPE html>
<html>
  <head>
    <style>
      textarea{
        width:30%;
        height:100px;
      }
    </style>
    <script>
      // encode string to base64
      function encode()
      {
        var txt = document.getElementById("txt1").value;
        var result = btoa(txt);
        document.getElementById("txt2").value = result;
      }
      // decode base64 back to original string
      function decode()
      {
        var txt = document.getElementById("txt3").value;
        var result = atob(txt);
        document.getElementById("txt4").value = result;
      }
    </script>
  </head>
  <body>
    <div>
      <textarea id="txt1">Some text to decode
      </textarea>
    </div>
    <div>
      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
    </div>
    <div>
      <textarea id="txt2">
      </textarea>
    </div>
    <br/>
    <div>
      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>
    </div>
    <div>
      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
    </div>
    <div>
      <textarea id="txt4">
      </textarea>
    </div>
  </body>
</html>

@Willem van der Veen 2018-09-23 08:35:26

What is URL encoding:

A URL should be encoded when there are special characters located inside the URL. For example:

console.log(encodeURIComponent('?notEncoded=&+'));

We can observe in this example that all characters except the string notEncoded are encoded with % signs. URL encoding is also known as percentage encoding because it escapes all special characters with a %. Then after this % sign every special character has a unique code

Why do we need URL encoding:

Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. In order to succesfully locate a resource on the web, it is necesarry to distinguish between when a character is meant as a part of string or part of the url structure.

How can we achieve URL encoding in JS:

JS offers a bunch of build in utility function which we can use to easily encode URL's. These are two convenient options:

  1. encodeURIComponent(): Takes a component of a URI as an argument and returns the encoded URI string.
  2. encodeURI(): Takes a URI as an argument and returns the encoded URI string.

Example and caveats:

Be aware of not passing in the whole URL (including scheme, e.g https://) into encodeURIComponent(). This can actually transform it into a not functional URL. For example:

// for a whole URI don't use encodeURIComponent it will transform
// the / characters and the URL won't fucntion properly
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));

// instead use encodeURI for whole URL's
console.log(encodeURI("http://www.random.com/specials&char.html"));

We can observe f we put the whole URL in encodeURIComponent that the foward slashes (/) are also converted to special characters. This will cause the URL to not function properly anymore.

Therefore (as the name implies) use:

  1. encodeURIComponent on a certain part of a URL which you want to encode.
  2. encodeURI on a whole URL which you want to encode.

@Gerard ONeill 2017-01-26 21:31:43

To encode a URL, as has been said before, you have two functions:

encodeURI()

and

encodeURIComponent()

The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.

With the first, you could copy the newly escaped URL into address bar (for example) and it would work. However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces. But for simple data when you want to preserve the URL nature of what you are escaping, this works.

The second is everything you need to do to make sure nothing in your string interfers with a URL. It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference. A URL encoded this way will no longer work as a URL without unescaping it.

So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.

I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.

@serg 2017-01-05 18:49:48

To prevent double encoding it's a good idea to decode the url before encoding (if you are dealing with user entered urls for example, which might be already encoded).

Lets say we have abc%20xyz 123 as input (one space is already encoded):

encodeURI("abc%20xyz 123")            //   wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // correct: "abc%20xyz%20123"

@Sangeet Shah 2015-09-10 06:41:37

Encode URL String

    var url = $(location).attr('href'); //get current url
    //OR
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string

@Maksym Kozlenko 2013-05-13 03:32:25

If you are using jQuery I would go for $.param method. It URL encodes an object mapping fields to values, which is easier to read than calling an escape method on each value.

$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1

@Maksym Kozlenko 2015-09-10 10:21:52

I think that example provided is sufficient. If you need more information about $.param on api.jquery.com/jquery.param

@Cyril Duchon-Doris 2017-01-04 16:36:08

Almost everyone uses jQuery and I feel more comfortable indeed with this instead of encoreURIComponent

@Mike Brennan 2011-05-29 23:54:43

Stick with encodeURIComponent(). The function encodeURI() does not bother to encode many characters that have semantic importance in URLs (e.g. "#", "?", and "&"). escape() is deprecated, and does not bother to encode "+" characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).

There is a nice explanation of the difference between encodeURI() and encodeURIComponent() elsewhere. If you want to encode something so that it can safely be included as a component of a URI (e.g. as a query string parameter), you want to use encodeURIComponent().

@Narayan Yerrabachu 2013-05-14 06:48:44

Similar kind of thing I tried with normal javascript

function fixedEncodeURIComponent(str){
     return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

@Asif Ashraf 2012-06-22 03:28:01

Nothing worked for me. All I was seeing was the HTML of the login page, coming back to the client side with code 200. (302 at first but the same Ajax request loading login page inside another Ajax request, which was supposed to be a redirect rather than loading plain text of the login page).

In the login controller, I added this line:

Response.Headers["land"] = "login";

And in the global Ajax handler, I did this:

$(function () {
    var $document = $(document);
    $document.ajaxSuccess(function (e, response, request) {
        var land = response.getResponseHeader('land');
        var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
        if(land) {
            if (land.toString() === 'login') {
                window.location = redrUrl;
            }
        }
    });
});

Now I don't have any issue, and it works like a charm.

@CMS 2008-12-02 02:49:54

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: [email protected]#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

@erickson 2008-12-02 04:55:45

The character encoding used with escape is variable. Stick with encodeURI and encodeURIComponent, which use UTF-8.

@opteronn 2010-03-05 20:10:15

Be careful. That escape converts non-ASCII characters into its Unicode escape sequences, like %uxxx.

@kevzettler 2011-01-30 05:05:08

I am using encodeURIComponent and noticing it will not encode pipe characters |

@nickf 2011-01-31 11:36:58

@kevzettler - why should it do that? The pipes aren't of semantic importance in a URI.

@fiatjaf 2013-07-05 21:45:57

does anybody use non-ASCII characters in URIs?

@Tseng 2013-09-04 14:43:55

@GiovanniP: People who allow German, French, Japanese, Chinese, Arabic characters as input and pass theses parameters via GET or POST.

@fiatjaf 2013-09-20 23:18:39

ah, ok, I thought you were talking about the domain/path parts, don't know why I thought this.

@John N 2014-10-29 19:30:23

encodeURIComponent() encoded the # and encodeURI() did not!

@Thor84no 2014-11-03 19:12:56

@fiatjaf Non-ASCII characters are perfectly legitimate in domains as well, though there will be an ASCII version stored in the DNS system. en.wikipedia.org/wiki/Internationalized_domain_name

@Dzeimsas Zvirblis 2015-12-16 15:42:18

NOTE: as of JavaScript version 1.5 escape() has been deprecated. Stick with either encodeURI() or encodeComponent(). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2695204 View
  • 2856 Score
  • 21 Answer
  • Tags:   javascript url

86 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6041520 View
  • 7522 Score
  • 86 Answer
  • Tags:   javascript arrays

31 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1100109 View
  • 4200 Score
  • 31 Answer
  • Tags:   http url uri urn rfc3986

15 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1391214 View
  • 3439 Score
  • 15 Answer
  • Tags:   git url git-remote

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

17 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1175494 View
  • 4638 Score
  • 17 Answer
  • Tags:   http url browser

3 Answered Questions

86 Answered Questions

[SOLVED] How do JavaScript closures work?

Sponsored Content