native encodeURIComponent
不支持编码感叹号 - !
我需要在 url 的查询参数中正确编码..
node.js querystring.stringify()
也没有..
是使用自定义函数的唯一方法 - https://github.com/kvz/phpjs/blob/master/functions/url/urlencode.js#L30 ?
最佳答案
您可以重新定义 native 函数以添加该功能。
下面是扩展 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's dev site 找到更多这方面的例子
关于javascript - 带感叹号的 encodeUriComponent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835737/