Removes a param from the search part of a URL - Node.js String

Node.js examples for String:URL String

Description

Removes a param from the search part of a URL

Demo Code



/**/*from  w w w  .  ja  va  2  s.c  o m*/
 * Removes a param from the search part of a URL.
 * @param {string} search Search part of a URL, e.g. location.search.
 * @param {string} name Param name.
 * @return {string} Modified search.
 */
function removeSearchParam(search, name) {
  if (search[0] === '?') {
    search = search.substring(1);
  }
  var parts = search.split('&');
  var res = [];
  for (var i = 0; i < parts.length; i++) {
    var pair = parts[i].split('=');
    if (pair[0] === name) {
      continue;
    }
    res.push(parts[i]);
  }
  search = res.join('&');
  if (search.length > 0) {
    search = '?' + search;
  }
  return search;
}

Related Tutorials