gpt4 book ai didi

javascript - 带感叹号的 encodeUriComponent?

转载 作者:数据小太阳 更新时间:2023-10-29 05:15:49 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com