7

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

node.jsquerystring.stringify()也不行..

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

4

1 回答 1

9

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

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

如果您希望代码更短,还可以添加一个新函数。
不过,这取决于你。

// 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

更多示例可以在Mozilla 的开发网站上找到

于 2013-09-16T19:44:46.410 回答