Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - encodeUriComponent with exclamation mark?

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 ?

like image 795
Kosmetika Avatar asked Sep 16 '13 19:09

Kosmetika


People also ask

Should I use encodeURI or encodeURIComponent?

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.

What does encodeURI do in Javascript?

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).

What is decodeURIComponent?

The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.


1 Answers

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

like image 102
Joe Simmons Avatar answered Sep 17 '22 20:09

Joe Simmons