JavaScript - 带感叹号的 encodeUriComponent?

7
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的开发者网站上找到更多此类示例。


1
是的,我知道可以覆盖它,但是想着 querystring 至少默认情况下具有这个功能,无论如何谢谢!;) - Kosmetika
关于你的原始问题,是的,我认为有必要创建一个自定义函数。 - Joe Simmons
7
为什么JavaScript函数无法正确处理这个问题?Erlang的URI编码器也不行! - sudo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接