原生的encodeURIComponent
不支持对感叹号 - !
进行编码,而我需要在URL查询参数中正确地对其进行编码。
node.js
中的querystring.stringify()
也不支持该功能。
是否唯一的解决方案是使用自定义函数,例如 - https://github.com/kvz/phpjs/blob/master/functions/url/urlencode.js#L30?
原生的encodeURIComponent
不支持对感叹号 - !
进行编码,而我需要在URL查询参数中正确地对其进行编码。
node.js
中的querystring.stringify()
也不支持该功能。
是否唯一的解决方案是使用自定义函数,例如 - https://github.com/kvz/phpjs/blob/master/functions/url/urlencode.js#L30?
您可以重新定义原生函数来添加该功能。
以下是扩展 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的开发者网站上找到更多此类示例。
querystring
至少默认情况下具有这个功能,无论如何谢谢!;) - Kosmetika