admin管理员组文章数量:1388859
Consider this URL below:
http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation
From the above URL I am extracing each query string values. For the Title query string, I need to split it on symbol underscore '_' and replace/join with a space. The problem is the "&". The javasript split stops right at '&' and escapes everything following.
var title = vars['Title'].split("_").join(" ");
gives me Meeting Planning
How do I split and join so I get Meeting Planning & Participation
Consider this URL below:
http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation
From the above URL I am extracing each query string values. For the Title query string, I need to split it on symbol underscore '_' and replace/join with a space. The problem is the "&". The javasript split stops right at '&' and escapes everything following.
var title = vars['Title'].split("_").join(" ");
gives me Meeting Planning
How do I split and join so I get Meeting Planning & Participation
-
6
you should encode the
&
as%26
as it has special meaning in URLs. – Daniel A. White Commented Apr 27, 2015 at 17:01 - 2 In addition to Daniel's ment, why are you doing split and join instead of: `var title = vars['Title'].replace("_", " ") which doesn't require turning the string into an array, then back into an array and simply iterates through the string. I think it will be a lot faster. – dmeglio Commented Apr 27, 2015 at 17:05
2 Answers
Reset to default 4You could simply replace _
with space, like below.
"Meeting_Planning_&_Participation".replace(/_/g, " ");
The whole code:
function getParam(query, key) {
var vars = query.split(/&(?![_])/);
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == key) return pair[1];
}
}
var url = "http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation";
var query = url.replace(/.*?\?/, "");
var title = getParam(query, "Title");
alert(title.replace(/_/g, " "));
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);
}
Usage:
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);
Output:
AJ_Swift
Meeting Planning & Participation
Demo:
http://codepen.io/tuga/pen/VLYyyL
本文标签: jqueryJavascript split and ampersand escapingStack Overflow
版权声明:本文标题:jquery - Javascript split and ampersand escaping - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744627839a2616363.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论