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

Share Improve this question asked Apr 27, 2015 at 16:58 AthapaliAthapali 1,0894 gold badges25 silver badges48 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 4

You 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