javascript - encodeUriComponent with exclamation m

2019-06-20 05:51发布

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 ?

1条回答
不美不萌又怎样
2楼-- · 2019-06-20 05:58

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

查看更多
登录 后发表回答