Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a parameter to the URL with JavaScript [duplicate]

Tags:

javascript

Original URL:

http://yourewebsite.php?id=10&color_id=1 

Resulting URL:

http://yourewebsite.php?id=10 

I got the function adding Param

function insertParam(key, value){     key = escape(key); value = escape(value);     var kvp = document.location.search.substr(1).split('&');     var i=kvp.length; var x; while(i--)      {         x = kvp[i].split('=');          if (x[0]==key)         {             x[1] = value;             kvp[i] = x.join('=');             break;         }     }     if(i<0) {kvp[kvp.length] = [key,value].join('=');}      //this will reload the page, it's likely better to store this until finished     document.location.search = kvp.join('&');  } 

but I need to function to remove Param

like image 814
Jows Avatar asked Jun 05 '13 13:06

Jows


People also ask

How to remove parameter from URL in JavaScript?

Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you. To use it, simply do something like this: var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL);

How do you remove something from a URL?

To request removal of a directory or site, click on the site in question, then go to Site configuration > Crawler access > Remove URL. If you enter the root of your site as the URL you want to remove, you'll be asked to confirm that you want to remove the entire site.


1 Answers

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

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);             }         }         if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");     }     return rtn; } 

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL); 

The var alteredURL will be the output you desire.

Hope it helps!

like image 78
Anthony Hessler Avatar answered Oct 05 '22 21:10

Anthony Hessler