考虑下面的这个 URL:
http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation
从上面的 URL 我提取每个查询字符串值。对于标题查询字符串,我需要将其拆分为符号下划线“_”并用空格替换/连接。问题是“&”。 javasript 拆分就在 '&' 处停止并转义后面的所有内容。
var title = vars['Title'].split("_").join(" ");
给我
Meeting Planning
我如何拆分和加入以便获得
Meeting Planning & Participation
最佳答案
function getQueryVariable(url, query) {
url = url.replace(/.*?\?/, "");
url = url.replace(/_&_/, "_%26_");
var vars = url.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == query) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
用法:
var url = "http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation "
var By = getQueryVariable(url, 'By');
var Title = getQueryVariable(url, 'Title');
Title = Title.replace(/_/ig, " ");
console.log(By);
console.log(Title);
输出:
AJ_Swift
Meeting Planning & Participation
演示:
http://codepen.io/tuga/pen/VLYyyL
关于Javascript拆分和&符号转义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29901753/