>  기사  >  웹 프론트엔드  >  javascript를 사용하여 URL 샘플 코드_javascript 기술의 매개변수 값 대체

javascript를 사용하여 URL 샘플 코드_javascript 기술의 매개변수 값 대체

WBOY
WBOY원래의
2016-05-16 17:02:161311검색

오늘 저는 URL의 일부 매개변수를 대체하기 위해 JavaScript를 사용해야 할 필요성을 느꼈습니다. 얼마 전에 인터넷에서 구현할 수 있는 parsUrl 함수를 찾았다는 것을 기억했습니다.

코드 복사 코드는 다음과 같습니다.

//分析url
functionparseURL(url) {
    var a = document.createElement('a');
    a.href = URL;
    return {
        소스: url,
        프로토콜: a.protocol.replace(':', ''),
        호스트: a.hostname,
        포트: a.port,
        쿼리: a.search,
        매개변수: (함수 () {
            var ret = {},
            seg = a.search.replace(/^?/, '').split(' &'),
            len = seg.length, i = 0, s
            for (; i < len; i ) {
              if (!seg[i]) { 계속; >               s = seg[i].split('=');
              ret[s[0]] = s[1];
           ret ; >        })( ),
        파일: (a.pathname.match(//([^/?#] )$/i) || [, ''])[1],
        해시: a.hash.replace ('#', ''),
        경로: a.pathname.replace(/^([^/])/, '/$1'),
        상대: (a.href.match(/tps ?://[^/] (. )/) || [, ''])[1],
        세그먼트: a.pathname.replace(/^//, '').split('/' )
    };
}

//替换myUrl中的同name参数值
function replacementUrlParams(myUrl, newParams) {
    /*
    for (var x in myUrl.params) {
        for (var y in newParams) {
            if (x.toLowerCase() == y.toLowerCase()) {
               myUrl.params[x] = newParams[y];
           }
        }
    }
    */

    for (var x in newParams) {
        var hasInMyUrlParams = false;
        for (var y in myUrl.params) {
            if (x.toLowerCase() == y.toLowerCase()) {
               myUrl.params[y] = newParams[x];
                hasInMyUrlParams = true;
                휴식;
           }
        }
        //原来没有参数则追加
       if (!hasInMyUrlParams) {
            myUrl.para ms[x] = newParams[x];
        }
    }
    var _result = myUrl.protocol "://" myUrl.host ":" myUrl.port myUrl.path "?";

    for (var p in myUrl.params) {
        _result = (p "=" myUrl.params[p] "&");
    }

    if (_result.substr(_result.length - 1) == "&") {
        _result = _result.substr(0, _result.length - 1);
    }

    if (myUrl.hash != "") {
        _result = "#" myUrl.hash;
    }
    return _result;
}

//辅助输출
function w(str) {
    document.write(str "
");
}

var myURL =parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
w("myUrl.file = " myURL.file)     // = 'index.html' 
w("myUrl.hash = " myURL.hash)     // = 'top'  
w(" myUrl.host = " myURL.host)     // = 'abc.com'
w("myUrl.query = " myURL.query)    // = '?id=255&m=hello'
w("myUrl .params = " myURL.params)   // = Object = { id: 255, m: hello }  
w("myUrl.path = " myURL.path)     // = '/dir/index.html'  
w("myUrl.segments = " myURL.segments) // = Array = ['dir', 'index.html']
w("myUrl.port = " myURL.port)     // = '8080'
w("myUrl.protocol = " myURL.protocol) // = 'http'  
w("myUrl.source = " myURL.source)   // = 'http://abc.com:8080/ dir/index.html?id=255&m=hello#top'

var _newUrl = replacementUrlParams(myURL, { id: 101, m: "World", page: 1,"page":2 });

w("
새 URL为:")
w(_newUrl); //http://abc.com:8080/dir/index.html?id=101&m=World&page=2#top   
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.