복붙노트

[JQUERY] URL에서 쿼리 문자열 제거

JQUERY

URL에서 쿼리 문자열 제거

해결법


  1. 1.이 얻을 수있는 쉬운 방법입니다 :

    이 얻을 수있는 쉬운 방법입니다 :

    function getPathFromUrl(url) {
      return url.split("?")[0];
    }
    

    어떤 쿼리 문자열이 존재하지 않는 경우에도 (원래의 질문의 일부) 해시를 제거하고자하는 사람들을 위해, 그것은 조금 더 필요합니다

    function stripQueryStringAndHashFromPath(url) {
      return url.split("?")[0].split("#")[0];
    }
    

    편집하다

    @caub (원래 @crl)는 간단한 콤보를 제안하는 쿼리 문자열 및 해시 모두를위한 작품 (그 사람이 그 문제를 가지고 경우 정규식을 사용하지만) :

    function getPathFromUrl(url) {
      return url.split(/[?#]/)[0];
    }
    

  2. 2.2 업데이트 : 포괄적 인 해답을 제공하기 위해 시도, 나는 다양한 답변에서 제안 된 세 가지 방법을 벤치마킹하고있다.

    2 업데이트 : 포괄적 인 해답을 제공하기 위해 시도, 나는 다양한 답변에서 제안 된 세 가지 방법을 벤치마킹하고있다.

    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');
    

    맥 OS X 10.6.2에 파이어 폭스 3.5.8에서 결과 :

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

    맥 OS X 10.6.2에 크롬 5.0.307.11의 결과 :

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

    URL에 쿼리 문자열을 포함하지 않는 경우 빈 문자열을 반환로 문자열 방법은 기능이 떨어진다는 것을 참고. 예상대로 다른 두 방법은 전체 URL을 반환합니다. 그러나 문자열 방법은 특히 파이어 폭스에서 가장 빠른 것을주의하는 것이 재미있다.

    1 UPDATE : 사실 로보에 의해 제안 된 분할 () 메소드는 쿼리 문자열이없는 경우에도 작동하기 때문에 나는 이전에 제안 하나가 더 나은 솔루션입니다 :

    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"
    

    원래 답변 :

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

  3. 3.이것은 오래된 질문이 될 수도 있지만 나는 검색어 매개 변수를 제거하려면이 방법을 시도했다. 잘 검색어 매개 변수의 제거와 결합으로 내가 다시로드를 필요에 따라 나를 위해 원활하게 작동하는 것 같다.

    이것은 오래된 질문이 될 수도 있지만 나는 검색어 매개 변수를 제거하려면이 방법을 시도했다. 잘 검색어 매개 변수의 제거와 결합으로 내가 다시로드를 필요에 따라 나를 위해 원활하게 작동하는 것 같다.

    window.location.href = window.location.origin + window.location.pathname;
    

    또한 나는 간단한 문자열 추가 작업을 사용하고 있기 때문에 나는 성능이 좋은 것 추측하고있다. 그러나 여전히 가치가이 답변에 미리와 비교


  4. 4.간단한 방법은 다음과 같이 할 수있다

    간단한 방법은 다음과 같이 할 수있다

    public static String stripQueryStringAndHashFromPath(String uri) {
     return uri.replaceAll(("(\\?.*|\\#.*)"), "");
    }
    

  5. 5.당신이 정규식에 있다면 ....

    당신이 정규식에 있다면 ....

    var newURL = testURL.match(new RegExp("[^?]+"))
    

  6. 6.

    var path = "path/to/myfile.png?foo=bar#hash";
    
    console.log(
        path.replace(/(\?.*)|(#.*)/g, "")
    );
    

  7. 7.(경로로 URL 앵커가 포함된다) backbone.js를 사용하는 경우, URL 쿼리 문자열이 나타날 수 있습니다 :

    (경로로 URL 앵커가 포함된다) backbone.js를 사용하는 경우, URL 쿼리 문자열이 나타날 수 있습니다 :

    해결책:

    window.location.href.replace(window.location.search, '');
    // run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
    

  8. 8.표준 URL을 사용하는 방법 :

    표준 URL을 사용하는 방법 :

    /**
     * @param {string} path - A path starting with "/"
     * @return {string}
     */
    function getPathname(path) {
      return new URL(`http://_${path}`).pathname
    }
    
    getPathname('/foo/bar?cat=5') // /foo/bar
    

  9. 9.당신이 URL에 복잡한 작업을 수행해야하는 경우, jQuery를 URL 파서 플러그인에 좀 걸릴 수 있습니다.

    당신이 URL에 복잡한 작업을 수행해야하는 경우, jQuery를 URL 파서 플러그인에 좀 걸릴 수 있습니다.


  10. 10.

    (() => {
            'use strict';
            const needle = 'SortOrder|Page'; // example
            if ( needle === '' || needle === '{{1}}' ) { 
                return; 
            }           
            const needles = needle.split(/\s*\|\s*/);
            const querystripper = ev => {
                        if (ev) { window.removeEventListener(ev.type, querystripper, true);}
                        try {
                              const url = new URL(location.href);
                              const params = new URLSearchParams(url.search.slice(1));
                              for (const needleremover of needles) {
                                    if (params.has(needleremover)) {
                                    url.searchParams.delete(needleremover);
                                        window.location.href = url;
                                }
                              }     
                        } catch (ex) { }
            };          
            if (document.readyState === 'loading') {
                     window.addEventListener('DOMContentLoaded', querystripper, true);
            } else {
                     querystripper();
            }
    })();
    

    그것은 또한 정규식 지원이, 어떻게 내가 해냈어.

  11. from https://stackoverflow.com/questions/2540969/remove-querystring-from-url by cc-by-sa and MIT license