Native encodeURIComponent
doesn't support encoding exclamation mark - !
which I need to have in url's query param encoded properly..
node.js querystring.stringify()
doesn't it as well..
is the only way to use custom function like - https://github.com/kvz/phpjs/blob/master/functions/url/urlencode.js#L30 ?
encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL. encodeURI should be used to encode a URI or an existing URL.
The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.
You could re-define the native function to add that functionality.
Here's an example of extending encodeURIComponent
to handle exclamation marks.
// adds '!' to encodeURIComponent
~function () {
var orig = window.encodeURIComponent;
window.encodeURIComponent = function (str) {
// calls the original function, and adds your
// functionality to it
return orig.call(window, str).replace(/!/g, '%21');
};
}();
encodeURIComponent('!'); // %21
You could also add a new function, if you wanted the code to be shorter.
That's up to you, though.
// separate function to add '!' to encodeURIComponent
// shorter then re-defining, but you have to call a different function
function encodeURIfix(str) {
return encodeURIComponent(str).replace(/!/g, '%21');
}
encodeURIfix('!'); // %21
More examples of this can be found at Mozilla's dev site
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With