0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

You should add a case-insensitive flag as well. This will also not work for trailing empty query parameters. But still a very good answer based on OP's example and request.
Query parameters name can contain more than lowercase and uppercase letters. I would recommend using the negated character class [^&=] since AFAIK only those characters have any special meaning in this context.
Thank you... you are a life saver.
1

I’d do it this way:

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

2 Comments

url.replace does not store the value. You need to do url=url.replace(...)
Thank you for your response.. i'll try this method also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.