Remove parameter url javascript

Remove querystring from URL

What is an easy way to remove the querystring from a Path in Javascript? I have seen a plugin for Jquery that uses window.location.search. I can not do that: The URL in my case is a variable that is set from AJAX.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc' 

12 Answers 12

An easy way to get this is:

function getPathFromUrl(url)

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)

@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]; >

2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3'; var i; // Testing the substring method i = 0; console.time('10k substring'); while (i < 10000) < testURL.substring(0, testURL.indexOf('?')); i++; >console.timeEnd('10k substring'); // Testing the split method i = 0; console.time('10k split'); while (i < 10000) < testURL.split('?')[0]; i++; >console.timeEnd('10k split'); // Testing the RegEx method i = 0; var re = new RegExp("[^?]+"); console.time('10k regex'); while (i < 10000) < testURL.match(re)[0]; i++; >console.timeEnd('10k regex'); 

Results in Firefox 3.5.8 on Mac OS X 10.6.2:

10k substring: 16ms 10k split: 25ms 10k regex: 44ms 

Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:

10k substring: 14ms 10k split: 20ms 10k regex: 15ms 

Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.

1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3'; testURL.split('?')[0]; // Returns: "/Products/List" var testURL2 = '/Products/List'; testURL2.split('?')[0]; // Returns: "/Products/List" 

Original Answer:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3'; testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List" 

Источник

URLSearchParams: delete() method

The delete() method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.

A parameter name and optional value are used to match parameters. If only a parameter name is specified, then all search parameters that match the name are deleted, along with their associated values. If both a parameter name and value are specified, then all search parameters that match both the parameter name and value are deleted.

Читайте также:  Карта-изображение

Note: This feature is available in Web Workers

Syntax

delete(name) delete(name, value) 

Parameters

The name of the parameters to be deleted.

The value that parameters must match, along with the given name, to be deleted.

Return value

Examples

Delete all parameters with specified name

This example shows how to delete all query parameters (and values) that have a particular name.

const logElement = document.getElementById("log"); function log(text)  logElement.innerText += `$text>\n`; > 
const url = new URL("https://example.com?foo=1&bar=2&foo=3"); const params = new URLSearchParams(url.search); log(`Query string (before):\t $params>`); params.delete("foo"); log(`Query string (after):\t $params>`); 

The log below shows that all parameters that have the name of foo are deleted.

Delete parameters with specified name and value

This example shows how to delete query parameters that match a particular name and value.

const logElement = document.getElementById("log"); function log(text)  logElement.innerText += `$text>\n`; > 
const url = new URL("https://example.com?foo=1&bar=2&foo=3&foo=1"); const params = new URLSearchParams(url.search); log(`Query string (before):\t $params>`); params.delete("foo", "1"); log(`Query string (after):\t $params>`); 

All parameters that match both the parameter name and value should be deleted (there is no reason to specify two parameters with the same name and value as shown above).

If your browser supports the value option, the «after» string should be bar=2&foo=3 . Otherwise the result will be the same as in the previous example ( bar=2 ).

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 26, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to remove some parameters from an URL string?

I have this var storing a string that represents a URL full of parameters. I’m using AngularJS, and I’m not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex? For example I need to remove &month=05 and also &year=2017 from: var url = «at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017»

7 Answers 7

var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017" var urlParts = url.split('?'); var params = new URLSearchParams(urlParts[1]); params.delete('month'); params.delete('year') var newUrl = urlParts[0] + '?' + params.toString() console.log(newUrl);

The advantage of using this API is that it works with and creates strings with correct percent encoding.

You can use this function that take 2 parameters: the param you are trying to remove and your source URL :

function removeParam(key, 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]; if (param === key) < params_arr.splice(i, 1); >> rtn = rtn + "?" + params_arr.join("&"); > return rtn; > var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"; var url2 = removeParam("month", url); var url3 = removeParam("year", url2); console.log(url3);

Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))

function removeParam(name, url) < return url.replace('/((&)*' + name + '=([^&]*))/g',''); >
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017" function removeParam(name, _url) < var reg = new RegExp("((&)*" + name + "=([^&]*))","g"); return _url.replace(reg,''); >url = removeParam('year', url); url = removeParam('month', url); document.getElementById('url-replace').innerHTML = url;

From the question: «Is there is any useful module to remove the unneeded URL parameters without having to use regex«.

var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"; var modifiedUrl = url.replace('&month=05','').replace('&year=2017',''); console.log(modifiedUrl);

Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url

const queryString = require('query-string'); console.log(location.search); //=> '?foo=bar' const parsed = queryString.parse(location.search); console.log(parsed); //=> console.log(location.hash); //=> '#token=bada55cafe' const parsedHash = queryString.parse(location.hash); console.log(parsedHash); //=> parsed.foo = 'unicorn'; parsed.ilike = 'pizza'; const stringified = queryString.stringify(parsed); //=> 'foo=unicorn&ilike=pizza' location.search = stringified; // note that `location.search` automatically prepends a question mark console.log(location.search); //=> '?foo=unicorn&ilike=pizza' 

Источник

Remove URL parameters without refreshing page

I am trying to remove everything after the «?» in the browser url on document ready. Here is what I am trying:

jQuery(document).ready(function($) < var url = window.location.href; url = url.split('?')[0]; >); 
jQuery(document).ready(function($) < var url = window.location.href; alert(url.split('?')[0]); >); 

Have two forms on one page and when one form is submitted it adds a product to cart and appends a long parameter to the url after the page refreshes. So I want to be able to remove that parameter when the document is ready and it starts with a ?

If you want to refresh the page, why wait for .ready() ? You don’t need to wait in order to redirect to a new URL or just use .pushState() as Joraid recommended.

17 Answers 17

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

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/ 
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 
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 
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"; 

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.

Источник

Оцените статью