Try it out:
encodeURIComponent(\"\'@#$%^&\");
If you try this out you will see all the special characters are encoded except for the single
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>
You can use btoa()
and atob()
, this encodes and decodes the given string including single quote.
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
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...
encodeURIComponent()
: Do not use. Use fixedEncodeURIComponent()
, as defined and explained by the MDN encodeURIComponent() Documentation, emphasis mine...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
While we're on the topic, also don't use encodeURI()
. MDN also has their own rewrite of it, as defined by the MDN encodeURI() Documentation. To quote their explanation...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
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:
As @Bergi wrote, you can just replace all the characters:
function encoePicture(pictureUrl)
{
var map=
{
'&': '%26',
'<': '%3c',
'>': '%3e',
'"': '%22',
"'": '%27'
};
var encodedPic = encodeURI(pictureUrl);
var result = encodedPic.replace(/[&<>"']/g, function(m) { return map[m];});
return result;
}