【问题标题】:javascript - encodeUriComponent with exclamation mark?javascript - 带感叹号的encodeUriComponent?
【发布时间】:2013-09-21 01:24:27
【问题描述】:

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

node.js querystring.stringify() 不也一样..

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

【问题讨论】:

    标签: javascript query-string special-characters urlencode encode


    【解决方案1】:

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

    这是一个扩展 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

    【讨论】:

    • 是的,我知道可以覆盖它,但我认为querystring 至少默认有这个,无论如何谢谢! ;)
    • Yw。至于你原来的问题,是的,我认为有必要创建一个自定义函数。
    • 为什么 JavaScript 函数不能正确处理这个问题? Erlang 的 URI 编码器也没有!
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多