javascript - 带感叹号的encodeUriComponent?

Kos*_*ika 6 javascript encode urlencode special-characters query-string

Native encodeURIComponent不支持编码感叹号 - !我需要在url的查询参数中正确编码感叹号.

node.js querystring.stringify()也不是..

是使用自定义函数的唯一方法 - https://github.com/kvz/phpjs/blob/master/functions/url/urlencode.js#L30

Joe*_*ons 7

您可以重新定义本机函数以添加该功能.

这是扩展encodeURIComponent处理感叹号的示例.

// 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
Run Code Online (Sandbox Code Playgroud)

如果希望代码更短,也可以添加新函数.
但是,这取决于你.

// 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
Run Code Online (Sandbox Code Playgroud)

更多这方面的例子可以在Mozilla的开发站点找到

  • 为什么JavaScript函数没有正确处理?Erlang的URI编码器也没有! (3认同)