Javascript encodeURIComponent doesn't encode single quotes

I'm not sure why you would want them to be encoded. If you only want to escape single quotes, you could use .replace(/'/g, "%27"). However, good references are:

  • When are you supposed to use escape instead of encodeURI / encodeURIComponent?
  • Comparing escape(), encodeURI(), and encodeURIComponent() at xkr.us
  • Javascript Madness: Query String Parsing #Javascript Encode/Decode Functions

You can use:

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

fixedEncodeURIComponent("'@#$%^&");

Check reference: http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/encodeURIComponent.html


I found a neat trick that never misses any characters. I tell it to replace everything except for nothing. I do it like this (URL encoding):

function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})}

function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})}

loader.value = encode(document.body.innerHTML);
<textarea id=loader rows=11 cols=55>www.WHAK.com</textarea>

Tags:

Javascript