How to Efficiently Remove a Query String by Key from a Url

How to efficiently remove a query string by Key from a Url?

This works well:

public static string RemoveQueryStringByKey(string url, string key)
{
var uri = new Uri(url);

// this gets all the query string key value pairs as a collection
var newQueryString = HttpUtility.ParseQueryString(uri.Query);

// this removes the key if exists
newQueryString.Remove(key);

// this gets the page path from root without QueryString
string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);

return newQueryString.Count > 0
? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
}

an example:

RemoveQueryStringByKey("https://www.google.co.uk/search?#hl=en&output=search&sclient=psy-ab&q=cookie", "q");

and returns:

https://www.google.co.uk/search?#hl=en&output=search&sclient=psy-ab

Remove querystring from URL

An easy way to get this is:

function getPathFromUrl(url) {
return url.split("?")[0];
}

For those who also wish to remove the hash (not part of the original question) when no querystring exists, that requires a little bit more:

function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}

EDIT

@caub (originally @crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):

function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}

How to remove query string parameters from the url?

Request.Querystring is read-only collection - You cannot modify that.

If you need to remove or change the param in querystring only way out is to trigger a new GET request with updated querystring - This means you will have to do Response.Redirect with updated URL. This will cause you lose the viewstate of the current page.

How to remove query string from a url?

The very helpful library furl makes it trivial to remove both query and fragment parts:

>>> furl.furl("https://hi.com/?abc=def#ghi").remove(args=True, fragment=True).url
https://hi.com/

How can I delete a query string parameter in JavaScript?

"[&;]?" + parameter + "=[^&;]+"

Seems dangerous because it parameter ‘bar’ would match:

?a=b&foobar=c

Also, it would fail if parameter contained any characters that are special in RegExp, such as ‘.’. And it's not a global regex, so it would only remove one instance of the parameter.

I wouldn't use a simple RegExp for this, I'd parse the parameters in and lose the ones you don't want.

function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {

var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);

//reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}

return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
}

Removing query string parameter from Url

router.replace() is to navigate by removing the current URL from the browser history stack and replace it with the argument route you pass to it.

The actual syntax is router.replace(url_location, onComplete, onAbort).

What you are doing is router.replace(my_param, null) which is removing the current URL from the history stack and replacing it with 'my_param' and for the onComplete callback you are passing a null

So do it like this:

this.$router.replace('/')

More info on programatic navigation

Javascript - Remove query string from current url

Unfortunately i cant able to do it with javascript or jquery. So i go through with php redirection, now it works.

<?php
if(isset($_POST['Submit'])) {
// actions
if(isset($_REQUEST['key']) && ($_REQUEST['key'] != "")) {
header('Refresh: 1;url='.$_SERVER['PHP_SELF']);
}
}
?>

Thanks all :)

Remove URL parameters without refreshing page

TL;DR

1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:

window.history.pushState({}, document.title, "/" + "my-new-url.html");

2- To replace current URL without adding it to history entries, use replaceState:

window.history.replaceState({}, document.title, "/" + "my-new-url.html");

3- Depending on your business logic, pushState will be useful in cases such as:

  • you want to support the browser's back button

  • you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL

  • allowing users to bookmark the page with the same parameters (to show the same contents)

  • to programmatically access the data through the stateObj then parse from the anchor


As I understood from your comment, you want to clean your URL without redirecting again.

Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/

www.example.com/old-page-name => can become =>  www.example.com/myNewPaage20180322.php
Background

We can use:

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.


.replaceState() is particularly useful when you want to update the
state object or URL of the current history entry in response to some
user action.



Code

To do that I will use The pushState() method for this example which works similarly to the following format:

var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );

Feel free to replace pushState with replaceState based on your requirements.

You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:

window.history.pushState({}, document.title, "/" + myNewURL );


Results

The previous two lines of code will make a URL such as:

https://domain.tld/some/randome/url/which/will/be/deleted/

To become:

https://domain.tld/my-new-url.php


Action

Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.

http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john

Will be:

http://www.someDomain.com/keepThisLastOne.php

Something like this will get it working:

 //fetch new URL
//refineURL() gives you the freedom to alter the URL string based on your needs.
var myNewURL = refineURL();

//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced.
window.history.pushState("object or string", "Title", "/" + myNewURL );


//Helper function to extract the URL between the last '/' and before '?'
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php'
//pseudo code: edit to match your URL settings

function refineURL()
{
//get full URL
var currURL= window.location.href; //get current address

//Get the URL between what's after '/' and befor '?'
//1- get URL after'/'
var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
//2- get the part before '?'
var beforeQueryString= afterDomain.split("?")[0];

return beforeQueryString;
}


UPDATE:

For one liner fans, try this out in your console/firebug and this page URL will change:

    window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.

An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).

window.location.href =  window.location.href.split("?")[0]; //"http://www.newurl.com";

Note 2:

Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string.
Chrome seems to be fine with an empty string.

how to remove query string arrays from url in javascript

function removeArrayParam(key, value, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("[]=")[0];
paramValue = params_arr[i].split("[]=")[1];
if (param === key && paramValue === value) {
params_arr.splice(i, 1);
}
}
if(params_arr.length) {
rtn = rtn + "?" + params_arr.join("&");
}
}
return rtn;
}

This function will give you the desired result. Just pass key, value and the hashless url.

var url = window.location.href;
var hash = window.location.hash;
var index_of_hash = url.indexOf(hash) || url.length;
var hashless_url = url.substr(0, index_of_hash);
var desired_url = removeArrayParam(key, value, unescape(hashless_url));


Related Topics



Leave a reply



Submit