首页 > web前端 > js教程 > 正文

用javascript替换URL中的参数值示例代码_javascript技巧

php中文网
发布: 2016-05-16 17:02:16
原创
1608人浏览过

今天遇到一个需要用javascript将url中的某些参数替换的需求,想起了不久前从网上淘到了一个parseUrl函数,正好可以借此实现,代码整理如下:

LobeHub
LobeHub

LobeChat brings you the best user experience of ChatGPT, OLLaMA, Gemini, Claude

LobeHub 201
查看详情 LobeHub
复制代码 代码如下:

//分析url
function parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function () {
            var ret = {},
            seg = a.search.replace(/^\?/, '').split('&'),
            len = seg.length, i = 0, s;
            for (; i                 if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;

        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
}

//替换myUrl中的同名参数值
function replaceUrlParams(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;
                break;
            }
        }
        //原来没有的参数则追加
        if (!hasInMyUrlParams) {
            myUrl.params[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 = replaceUrlParams(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   
相关标签:
java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号