Javascript separation and ampersand

Consider the following URL:

http://test/Preview.aspx?By=AJ_Swift&Title=Meeting_Planning_&_Participation 

      

From the above url, I add the values โ€‹โ€‹of each query string. For the header query string, I need to split it with the underscore "_" and replace / concatenate with a space. The problem is "&". The javasript splitting stops right at '&' and avoids all of the following.

var title = vars['Title'].split("_").join(" ");

      

gives me Meeting Planning

How do I split and join, so I get Meeting Planning & Participation

+3


source to share


2 answers


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);
}

      




Using:

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

+2


source


You can just replace _

with a space like below.

"Meeting_Planning_&_Participation".replace(/_/g, " ");

      

All 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, " "));
      

Run codeHide result


+4


source







All Articles