Programming

JavaScript에서 쿼리 문자열 매개 변수를 어떻게 삭제합니까?

procodes 2020. 7. 26. 14:01
반응형

JavaScript에서 쿼리 문자열 매개 변수를 어떻게 삭제합니까?


정규 표현식을 사용하는 것보다 표준 JavaScript의 URL 문자열에서 쿼리 문자열에서 매개 변수를 삭제하는 더 좋은 방법이 있습니까?

여기 지금까지 내가 테스트에서 작동하는 것 같지만 쿼리 문자열 구문 분석을 재발 명하고 싶지 않습니다!

function RemoveParameterFromUrl( url, parameter ) {

    if( typeof parameter == "undefined" || parameter == null || parameter == "" ) throw new Error( "parameter is required" );

    url = url.replace( new RegExp( "\\b" + parameter + "=[^&;]+[&;]?", "gi" ), "" ); "$1" );

    // remove any leftover crud
    url = url.replace( /[&;]$/, "" );

    return url;
}

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

매개 변수 'bar'가 다음과 일치하므로 위험합니다.

?a=b&foobar=c

또한 parameter'.'와 같이 RegExp에 특수한 문자가 포함되어 있으면 실패합니다 . 그리고 그것은 전역 정규 표현식이 아니므로 매개 변수의 인스턴스 하나만 제거합니다.

나는 이것을 위해 간단한 RegExp를 사용하지 않을 것이다. 나는 매개 변수를 파싱하고 원하지 않는 것을 잃어 버릴 것이다.

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;
}

bobince 답변에서 복사했지만 쿼리 문자열에서 물음표를 지원합니다.

http://www.google.com/search?q=test???+something&aq=f

URL에 둘 이상의 물음표가있는 것이 유효합니까?

function removeUrlParameter(url, parameter) {
  var urlParts = url.split('?');

  if (urlParts.length >= 2) {
    // Get first part, and remove from array
    var urlBase = urlParts.shift();

    // Join it back up
    var queryString = urlParts.join('?');

    var prefix = encodeURIComponent(parameter) + '=';
    var parts = queryString.split(/[&;]/g);

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

    url = urlBase + '?' + parts.join('&');
  }

  return url;
}

최신 브라우저URLSearchParams검색 매개 변수와 작동 하는 인터페이스를 제공합니다 . 가 어떤 delete방법을 이름으로 제거합니다의 PARAM 그.

if (typeof URLSearchParams !== 'undefined') {
  const params = new URLSearchParams('param1=1&param2=2&param3=3')
  
  console.log(params.toString())
  
  params.delete('param2')
  
  console.log(params.toString())

} else {
  console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)
}


정규식 솔루션에 큰 문제가 보이지 않습니다. 그러나 조각 식별자 ( #. 뒤에있는 텍스트)를 유지하는 것을 잊지 마십시오 .

내 해결책은 다음과 같습니다.

function RemoveParameterFromUrl(url, parameter) {
  return url
    .replace(new RegExp('[?&]' + parameter + '=[^&#]*(#.*)?$'), '$1')
    .replace(new RegExp('([?&])' + parameter + '=[^&]*&'), '$1');
}

그리고 bobince의 요점으로, 네- .매개 변수 이름의 문자 를 이스케이프해야 합니다.


정규식 솔루션에 관심이있는 사람은이 기능을 결합하여 querystring 매개 변수를 추가 / 제거 / 업데이트했습니다. 값을 제공하지 않으면 매개 변수가 제거되고 매개 변수를 제공하면 매개 변수가 추가 / 업데이트됩니다. URL을 제공하지 않으면 window.location에서 가져옵니다. 이 솔루션은 또한 URL 앵커를 고려합니다.

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}

최신 정보

쿼리 문자열에서 첫 번째 매개 변수를 제거 할 때 버그가 발생하여 정규식을 수정하고 수정 사항을 포함하도록 테스트했습니다.

업데이트 2

해시 태그 바로 앞에 쿼리 스트링 변수를 제거 할 때 해시 태그 기호가 손실되는 상황을 해결하기위한 @schellmax 업데이트


다음을 사용하여 URL을 변경할 수 있습니다.

window.history.pushState({}, document.title, window.location.pathname);

이렇게하면 검색 매개 변수없이 URL을 덮어 쓸 수 있습니다 .GET 매개 변수를 사용한 후 URL을 정리하는 데 사용합니다.


URI에서 key = val 매개 변수를 제거한다고 가정하십시오.

function removeParam(uri) {
   return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}

이 질문 과이 github 요점을 기반으로 매개 변수를 추가하고 제거하는 완전한 기능은 다음과 같습니다. https://gist.github.com/excalq/2961415

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {

        updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty

            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it

            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string

            params = urlQueryString + '&' + newParam;

        }

    }
    window.history.replaceState({}, "", baseUrl + params);
};

다음과 같은 매개 변수를 추가 할 수 있습니다.

updateQueryStringParam( 'myparam', 'true' );

그리고 이것을 다음과 같이 제거하십시오.

updateQueryStringParam( 'myparam', null );

이 스레드에서 많은 사람들은 정규 표현식이 아마도 최상의 / 안정적인 솔루션이 아니라고 말했습니다 ... 그래서이 문제에 약간의 결함이 있는지 100 % 확신하지는 않지만 테스트 한 한 꽤 잘 작동합니다.


내가 사용하고있는 것은 다음과 같습니다.

if (location.href.includes('?')) { 
    history.pushState({}, null, location.href.split('?')[0]); 
}

원래 URL : http://www.example.com/test/hello?id=123&foo=bar
도착 URL : http://www.example.com/test/hello


jQuery 사용하기 :

function removeParam(key) {
    var url = document.location.href;
    var params = url.split('?');
    if (params.length == 1) return;

    url = params[0] + '?';
    params = params[1];
    params = params.split('&');

    $.each(params, function (index, value) {
        var v = value.split('=');
        if (v[0] != key) url += value + '&';
    });

    url = url.replace(/&$/, '');
    url = url.replace(/\?$/, '');

    document.location.href = url;
}

함수로서의 위의 버전

function removeURLParam(url, param)
{
 var urlparts= url.split('?');
 if (urlparts.length>=2)
 {
  var prefix= encodeURIComponent(param)+'=';
  var pars= urlparts[1].split(/[&;]/g);
  for (var i=pars.length; i-- > 0;)
   if (pars[i].indexOf(prefix, 0)==0)
    pars.splice(i, 1);
  if (pars.length > 0)
   return urlparts[0]+'?'+pars.join('&');
  else
   return urlparts[0];
 }
 else
  return url;
}

URI 조작은 표면에서 직접 수행하는 것보다 복잡하므로 라이브러리를 사용하여 URI 조작을 수행해야합니다. http://medialize.github.io/URI.js/를 살펴보십시오 .


내가 볼 수 있듯이 위의 어느 것도 정상적인 매개 변수 및 배열 매개 변수를 처리 할 수 ​​없습니다. 여기 하나가 있습니다.

function removeURLParameter(param, url) {
    url = decodeURI(url).split("?");
    path = url.length == 1 ? "" : url[1];
    path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
    path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
    path = path.replace(/^&/, "");
    return url[0] + (path.length
        ? "?" + path
        : "");
}

function addURLParameter(param, val, url) {
    if(typeof val === "object") {
        // recursively add in array structure
        if(val.length) {
            return addURLParameter(
                param + "[]",
                val.splice(-1, 1)[0],
                addURLParameter(param, val, url)
            )
        } else {
            return url;
        }
    } else {
        url = decodeURI(url).split("?");
        path = url.length == 1 ? "" : url[1];
        path += path.length
            ? "&"
            : "";
        path += decodeURI(param + "=" + val);
        return url[0] + "?" + path;
    }
}

사용 방법:

url = location.href;
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

url = removeURLParameter("sold", url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = removeURLParameter("tags", url)
    -> http://example.com/

url = addURLParameter("tags", ["single", "promo"], url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = addURLParameter("sold", 1, url)
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

물론 매개 변수를 업데이트하려면 제거하고 추가하십시오. 더미 기능을 자유롭게 만드십시오.


All of the responses on this thread have a flaw in that they do not preserve anchor/fragment parts of URLs.

So if your URL looks like:

http://dns-entry/path?parameter=value#fragment-text

and you replace 'parameter'

you will lose your fragment text.

The following is adaption of previous answers (bobince via LukePH) that addresses this problem:

function removeParameter(url, parameter)
{
  var fragment = url.split('#');
  var urlparts= fragment[0].split('?');

  if (urlparts.length>=2)
  {
    var urlBase=urlparts.shift(); //get first part, and remove from array
    var queryString=urlparts.join("?"); //join it back up

    var prefix = encodeURIComponent(parameter)+'=';
    var pars = queryString.split(/[&;]/g);
    for (var i= pars.length; i-->0;) {               //reverse iteration as may be destructive
      if (pars[i].lastIndexOf(prefix, 0)!==-1) {   //idiom for string.startsWith
        pars.splice(i, 1);
      }
    }
    url = urlBase + (pars.length > 0 ? '?' + pars.join('&') : '');
    if (fragment[1]) {
      url += "#" + fragment[1];
    }
  }
  return url;
}

Here a solution that:

  1. uses URLSearchParams (no difficult to understand regex)
  2. updates the URL in the search bar without reload
  3. maintains all other parts of the URL (e.g. hash)
  4. removes superflous ? in query string if the last parameter was removed
function removeParam(paramName) {
    let searchParams = new URLSearchParams(window.location.search);
    searchParams.delete(paramName);
    if (history.replaceState) {
        let searchString = searchParams.toString().length > 0 ? '?' + searchParams.toString() : '';
        let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname +  searchString + window.location.hash;
        history.replaceState(null, '', newUrl);
    }
}

Note: as pointed out in other answers URLSearchParams is not supported in IE, so use a polyfill.


A modified version of solution by ssh_imov

function removeParam(uri, keyValue) {
      var re = new RegExp("([&\?]"+ keyValue + "*$|" + keyValue + "&|[?&]" + keyValue + "(?=#))", "i"); 
      return uri.replace(re, '');
    }

Call like this

removeParam("http://google.com?q=123&q1=234&q2=567", "q1=234");
// returns http://google.com?q=123&q2=567

This returns the URL w/o ANY GET Parameters:

var href = document.location.href;
var search = document.location.search;
var pos = href.indexOf( search );
if ( pos !== -1 ){
    href = href.slice( 0, pos );
    console.log( href );
}

This is a clean version remove query parameter with the URL class for today browsers:

function removeUrlParameter(url, paramKey)
{
  var r = new URL(url);
  r.searchParams.delete(paramKey);
  return r.href;
}

URLSearchParams not supported on old browsers

https://caniuse.com/#feat=urlsearchparams

IE, Edge (below 17) and Safari (below 10.3) do not support URLSearchParams inside URL class.

Polyfills

URLSearchParams only polyfill

https://github.com/WebReflection/url-search-params

Complete Polyfill URL and URLSearchParams to match last WHATWG specifications

https://github.com/lifaon74/url-polyfill


If you're into jQuery, there is a good query string manipulation plugin:


function removeQueryStringParameter(uri, key, value) 
{

var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");

    var separator = uri.indexOf('?') !== -1 ? "&" : "?";

    if (uri.match(re)) {

        return uri.replace(re, '');

    }
}

참고URL : https://stackoverflow.com/questions/1634748/how-can-i-delete-a-query-string-parameter-in-javascript

반응형