복붙노트

[JQUERY] 자바 스크립트의 URL을 구문 분석

JQUERY

자바 스크립트의 URL을 구문 분석

해결법


  1. 1.당신은,는 A-요소를 만드는 트릭을 사용하여 여기에 URL을 추가 한 다음 그 위치 개체를 사용할 수 있습니다.

    당신은,는 A-요소를 만드는 트릭을 사용하여 여기에 URL을 추가 한 다음 그 위치 개체를 사용할 수 있습니다.

    function parseUrl( url ) {
        var a = document.createElement('a');
        a.href = url;
        return a;
    }
    
    parseUrl('http://example.com/form_image_edit.php?img_id=33').search
    

    의지 출력 : img_id = 33

    또한 자바 스크립트에서 parse_url 함수를 얻을 수 php.js를 사용할 수 있습니다.

    난 당신이 슈퍼 간단한 URL 처리보다 더 많은 작업을 수행 할 필요가있는 경우 우수한 URI.js 라이브러리를 사용하는 것이 좋습니다.


  2. 2.당신의 문자열은 다음의를 호출하는 경우

    당신의 문자열은 다음의를 호출하는 경우

    var id = s.match(/img_id=([^&]+)/)[1]
    

    당신에게 그것을 줄 것이다.


  3. 3.이 시도:

    이 시도:

    var url = window.location;
    var urlAux = url.split('=');
    var img_id = urlAux[1]
    

  4. 4.안뜨기 (A 자바 스크립트 URL 파서) 플러그인 좋은 jQuery를 기존 .This 유틸리티는 두 가지 방법으로 사용할 수 있습니다 - jQuery로 또는없이 ...

    안뜨기 (A 자바 스크립트 URL 파서) 플러그인 좋은 jQuery를 기존 .This 유틸리티는 두 가지 방법으로 사용할 수 있습니다 - jQuery로 또는없이 ...


  5. 5.짧막 한 농담:

    짧막 한 농담:

    location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})
    

  6. 6.구글에서있어,이 방법을 사용하려고

    구글에서있어,이 방법을 사용하려고

    function getQuerystring2(key, default_) 
    { 
        if (default_==null) 
        { 
            default_=""; 
        } 
        var search = unescape(location.search); 
        if (search == "") 
        { 
            return default_; 
        } 
        search = search.substr(1); 
        var params = search.split("&"); 
        for (var i = 0; i < params.length; i++) 
        { 
            var pairs = params[i].split("="); 
            if(pairs[0] == key) 
            { 
                return pairs[1]; 
            } 
        } 
    
    
    return default_; 
    }
    

  7. 7.이 고베의 대답에 몇 가장자리 케이스를 수정해야합니다 :

    이 고베의 대답에 몇 가장자리 케이스를 수정해야합니다 :

    function getQueryParam(url, key) {
      var queryStartPos = url.indexOf('?');
      if (queryStartPos === -1) {
        return;
      }
      var params = url.substring(queryStartPos + 1).split('&');
      for (var i = 0; i < params.length; i++) {
        var pairs = params[i].split('=');
        if (decodeURIComponent(pairs.shift()) == key) {
          return decodeURIComponent(pairs.join('='));
        }
      }
    }
    
    getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
    // outputs "33"
    

  8. 8.나는 도서관, URL.js, 당신이 그것을 사용할 수있는 구문 분석 자바 스크립트 URL을 썼다.

    나는 도서관, URL.js, 당신이 그것을 사용할 수있는 구문 분석 자바 스크립트 URL을 썼다.

    예:

    url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"
    

  9. 9.이런 식으로 뭔가가 당신을 위해 작동합니다. 여러 쿼리 문자열 값이있는 경우에도이 함수는 원하는 키의 값을 반환해야합니다.

    이런 식으로 뭔가가 당신을 위해 작동합니다. 여러 쿼리 문자열 값이있는 경우에도이 함수는 원하는 키의 값을 반환해야합니다.

    function getQSValue(url) 
    {
        key = 'img_id';
        query_string = url.split('?');
        string_values = query_string[1].split('&');
        for(i=0;  i < string_values.length; i++)
        {
            if( string_values[i].match(key))
                req_value = string_values[i].split('=');    
        }
        return req_value[1];
    }
    

  10. 10.당신은 http://plugins.jquery.com/url 플러그인 jQuery를 사용할 수 있습니다. $ .URL ( "? img_id")는 33를 반환합니다

    당신은 http://plugins.jquery.com/url 플러그인 jQuery를 사용할 수 있습니다. $ .URL ( "? img_id")는 33를 반환합니다


  11. 11.

    function parse_url(str, component) {
      //       discuss at: http://phpjs.org/functions/parse_url/
      //      original by: Steven Levithan (http://blog.stevenlevithan.com)
      // reimplemented by: Brett Zamir (http://brett-zamir.me)
      //         input by: Lorenzo Pisani
      //         input by: Tony
      //      improved by: Brett Zamir (http://brett-zamir.me)
      //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
      //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
      //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
      //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
      //             note: a seriously malformed URL.
      //             note: Besides function name, is essentially the same as parseUri as well as our allowing
      //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
      //        example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
      //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    
      var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
          'relative', 'path', 'directory', 'file', 'query', 'fragment'
        ],
        ini = (this.php_js && this.php_js.ini) || {},
        mode = (ini['phpjs.parse_url.mode'] &&
          ini['phpjs.parse_url.mode'].local_value) || 'php',
        parser = {
          php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
          strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
          loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
        };
    
      var m = parser[mode].exec(str),
        uri = {},
        i = 14;
      while (i--) {
        if (m[i]) {
          uri[key[i]] = m[i];
        }
      }
    
      if (component) {
        return uri[component.replace('PHP_URL_', '')
          .toLowerCase()];
      }
      if (mode !== 'php') {
        var name = (ini['phpjs.parse_url.queryKey'] &&
          ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
        parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
        uri[name] = {};
        query = uri[key[12]] || '';
        query.replace(parser, function($0, $1, $2) {
          if ($1) {
            uri[name][$1] = $2;
          }
        });
      }
      delete uri.source;
      return uri;
    }
    

    참고


  12. 12.

    var url = window.location;
    var urlAux = url.split('=');
    var img_id = urlAux[1]
    

    나를 위해 일했다. 그러나 첫 번째 VAR는 VAR URL = window.location.href를해야한다


  13. 13.웹 근로자 URL 파싱을위한 유틸 URL을 제공합니다.

    웹 근로자 URL 파싱을위한 유틸 URL을 제공합니다.

  14. from https://stackoverflow.com/questions/6644654/parse-an-url-in-javascript by cc-by-sa and MIT license