Search code examples
javascriptencodeuricomponent

encode parenthesis underscore tilt star with encodeURIComponent


encodeURIComponent escapes all characters except the following: - _ . ! ~ * ' ( )

But is it possible to extend the functionality encode the above special characters as well.

I know i can do something like this:

encodeURIComponent(str).replace(/\(/g, "%28").replace(/\)/g, "%29");

but I want functionality like this, without using additional functions on the encodeURIComponent

encodeURIComponent(str);

Solution

    1. You should create your own function.
    2. You should create your own function, really.
    3. If you really know what you're doing, go to step 1.

    Don't say I didn't warn you; there be dragons here:

    (function() {
        var _fn = encodeURIComponent;
    
        window.encodeURIComponent = function(str) {
            return _fn(str).replace(/\(/g, "%28").replace(/\)/g, "%29");
        };
    }());