javascript :如何替换会破坏 URL 中的查询字符串的特殊 symbols/characters

javascript : how to replace special symbols/characters that will break your query string in your URL

我的 URL 中有这个组件 --

var myType="Air B&B";
var myID="RestInPeace";
var myURL="http://myhome.com?type="+myType+"&name="+myID;
alert(myURL);  //http://myhome.com?type=Air B&B&id=RestInPeace

myType 中的“&”破坏了您在此处的查询:

http://myhome.com?type=Air B&B&id=RestInPeace

页面依赖id来定位记录。它不会得到它,因为类型中的“&”破坏了查询!需要处理 myType 中的任何 uri 敏感字符,以免中断查询。

由于第二个参数不是加载记录的关键,我将牺牲类型参数中的'&'。

这些字符将中断您在 URI 中的查询:$ & : ' " < > [ ] + { }。请参阅下面通过转义 [] 内的这些符号来快速替换: 表示 []

中的任何一个符号
var myType="Air B&B";
var myID="RestInPeace";
var myURL="http://myhome.com?type="+myType.replace(/[$\&\'\"\:\<\>\[\]\{\}\+]/g, '^')+"&name="+myID;
alert(myURL);  //http://myhome.com?type=Air B^B&name=RestInPeace

现在 myType 中的“&”被替换了。并保留查询。

http://myhome.com?type=Air B^B&name=RestInPeace

最好的方法是使用 URL()。 使用

创建一个新的 URL
var myURL = new URL('http://myhome.com');

然后附加搜索参数,例如

var myType="Air B&B";
var myID="RestInPeace";
myURL.searchParams.set('type',myType);
myURL.searchParams.set('name',myID);

这将return一个像

这样的对象
hash: ""
host: "myhome.com"
hostname: "myhome.com"
href: "http://myhome.com/?type=Air+B%26B&name=RestInPeace"
origin: "http://myhome.com"
password: ""
pathname: "/"
port: ""
protocol: "http:"
search: "?type=Air+B%26B&name=RestInPeace"
searchParams: URLSearchParams {}
username: ""

所以基本上它会自动保留您的查询

从 1.5 版开始(ECMA-262 3rd edition, December 1999) JavaScript supports the functions encodeURI() and encodeURIComponent() 正是为了这个工作。我不知道你们两个怎么能监督这个。

另见问题Should I use encodeURI or encodeURIComponent for encoding URLs?