javascript - 带感叹号的 encodeUriComponent?

标签 javascript query-string special-characters urlencode encode

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/

相关文章:

coldfusion - 具有特殊字符的查询中的访问列?

php - XML 解析错误 : undefined entity - special characters

javascript - 将组合器与 $(this) 一起使用

backbone.js - 如何将查询字符串传递给backbone.js 路由

asp.net - Internet Explorer 9 中 URL 查询字符串值的 UTF-8 字符编码问题

json - 将 JSON 序列化为查询字符串的标准化方法?

iphone - 从 CMS 获取文本中的特殊字符问题

javascript - 将带有平均数据的新对象添加到 JavaScript 数组中

javascript - 将 ID 传递给 Angular JS 中的函数

javascript - 在react.js中使用select和option时弹出窗口不会打开