Kishore L
Kishore L

Reputation: 188

Remove a particular part of a url string using javascript

In the following string,

http://blahblah.in/folder1/data?number=1&name= &customerId=123

I'm trying to validate the URL, that is, if any querystring parameter does not have a value, remove that parameter from the URL.

The resultant URL will be

http://blahblah.in/folder1/data?number=1&customerId=123

I tried to solve the above problem with the following code, and I know I have a mistake somewhere - can you help me find it?

var url = "http://blahblah.in/folder1/data?number=1&name= &customerId=123";


var tempQuestion = url.split("?");
 var temp = tempQuestion[1].split("=");
var temp2="";
var leng = temp.length;
for(i=0;i<leng;i++){


    if(temp[i].charAt(0)!="&")
        temp2 = temp2.concat(temp[i],"=");
    else 
    {
        temp2 = temp2.concat(temp[i],"");
        var x = temp2.split("&");
        temp2 = temp2.concat(x[0],"=");
    }

}

var result= tempQuestion[0].concat("?",temp2);

Upvotes: 0

Views: 87

Answers (2)

Iso
Iso

Reputation: 3238

I’d do it this way:

url.replace(/\?.*/, function(qs) {
  return qs.split('&').filter(function(parameterTuple) {
    return parameterTuple.split('=')[1];
  }).join('&');
});

Upvotes: 1

leo.fcx
leo.fcx

Reputation: 6457

Just use regular expressions as follows:

    var url = 'http://blahblah.in/folder1/data?number=1&name=&other=&something=&customerId=123'
    url = url.replace(/[a-z]*=&/g,"");
    console.log(url)
    // result is: http://blahblah.in/folder1/data?number=1&customerId=123

Upvotes: 3

Related Questions