javascript - encodeUriComponent with exclamation mark?

谁说我不能喝 提交于 2019-12-23 09:10:11

问题


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:


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



来源:https://stackoverflow.com/questions/18835737/javascript-encodeuricomponent-with-exclamation-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!