转义 ' 和 & 以及 url 中的类似字符

Escaping ' and & and similar characters in url

我需要一种在 url 中同时编码 '& 的方法。检查以下示例:

// "get_records.php?artist=Mumford%20%26%20Sons"
"get_records.php?artist=" + encodeURIComponent("Mumford & Sons"); 

// "get_records.php?artist=Gigi%20D'Agostinos"
"get_records.php?artist=" + encodeURIComponent("Gigi D'Agostino");

encodeURIComponent 不编码 '。我可以改用 escape,但我想它已被弃用。在这种情况下我该怎么办?创建自定义编码器?


我也会转义其他字符::/.,!,例如,对于以下内容字符串

"11:59"
"200 km/h in the Wrong Lane"
"P.O.D."
"Everybody Else Is Doing It, So Why Can't We"
"Up!"

因此,创建自定义编码器似乎是最佳选择。我可以使用其他方法吗?

您必须自己实现此功能。

MDN 涵盖了这个确切的主题。将他们的提议扩展到涵盖 & 角色和其他角色应该是微不足道的。

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

Source

您可以在创建前替换字符 URL。

' = %27

检查这个: http://www.w3schools.com/tags/ref_urlencode.asp