https://ru.stackoverflow.com/questions/ask?param=myparam&test=testname

There are functions for extracting all parameters, but how to delete a specific one?

maybe there is a ready-made function to not use regulars? In this case, I need to remove the myparam parameter, which can stand in any part not only first. At the output, the line should look like:

https://ru.stackoverflow.com/questions/ask?test=testname

  • var hash = {}; url.split('?')[1].split('&').foreach((e)=>{hash[e.split('=')[0]]=e.split('=')[1]}) var hash = {}; url.split('?')[1].split('&').foreach((e)=>{hash[e.split('=')[0]]=e.split('=')[1]}) Well, and then delete from the hash, and collect back. :-) - Chad
  • Do you need to delete in the address bar of your browser, or just in a variable? - Dmitry Polyanin

2 answers 2

 function removeParam(key, sourceURL) { var splitUrl = sourceURL.split('?'), rtn = splitUrl[0], param, params_arr = [], queryString = (sourceURL.indexOf("?") !== -1) ? splitUrl[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 = "http://someUrl.ru?param1=123&param2=234&param3=435"; var url1 = removeParam("param1", url); var url2 = removeParam("param2", url); var url3 = removeParam("param3", url); console.log(url); console.log(url1); console.log(url2); console.log(url3); var testUrl = 'https://ru.stackoverflow.com/questions/ask?param=myparam&test=testname'; var urlTest = removeParam("param", testUrl); console.log(urlTest); 

  • and how to insert a new URL into the address bar, but do not reload the page? (just paste) - user9113950
  • window.history.pushState ({}, document.title, новый url ); - Sergey Glazirin
  • one
    sourceURL.split('?') call several times in a function, it is better to bring it up and call it once, and then use the result, and that results in unnecessary calls - Dmitry Polyanin
  • one
    pushState inserts the history as a new history object, that is, if you click back, it will transfer not the first address, but the first will send back to the new one, thus the history will be broken, and replaceState replaces the current one without inserting a new one. - Dmitry Polyanin
  • @DmitryPolyanin, perhaps you are right, the use of replaceState will be better. Thanks for improving the answer. - Sergey Glazirin

with limited browser support, you can

 var link = 'https://ru.stackoverflow.com/questions/ask?param=myparam&test=testname'; var url = new URL(link); url.searchParams.delete('test'); console.log(url);