Skip to content
Advertisement

How to remove ? (question mark) from url when it is not followed by any parameters?

I have a form that sends a get request to the server. the input parameters are sent to the server in QueryString.

This is my form:

<form action="host-name/Home/Browse"  onsubmit="removeEmptyParameters()">
    <input type="text" name="Term" /> 
    <input type="text" name="Address" /> 
    <input type="submit" value="submit">
</form>

Before submitting the form, the following JavaScript method is executed to remove the empty input parameters from the form:

function removeEmptyParameters() {
    // set the name attribute = "" for empty inputs, so they won't be posted to server
    $('form').find('input').each(function () {
        if (this.value === "") {
            $(this).attr('name', '');
        }
    });
}

So if user enters some input, the request would be:

ulr: host-name/Home/Browse?Term=some-term&Address=some-address

If all the inputs are empty, the following url is sent to server:

ulr: host-name/Home/Browse?

This works fine, but I would like to remove ? from url, so it would be clean. Is it possible to do this?

Advertisement

Answer

You can use the String.prototype.slice() method to achieve this. If the last character of your url is ‘?’, you can remove it from the url string.

let url = "www.someurl.com?";
let length = url.length;
if(url.charAt(length-1)==='?')
url=url.slice(0,length-1);
console.log(url);

Please visit the following MDN link for more details on slice(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

I am not sure if this is the best solution, but you can try to use window.location.href to redirect incase the parameters are empty. In that way, it would be possible to keep the url clean.

Advertisement