• 用javascript替换URL中的参数值


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

        //分析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 < len; 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
    作者:菩提树下的杨过
    出处:http://yjmyzz.cnblogs.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Spring5源码分析(011)——IoC篇之解析bean标签总览
    Spring5源码分析(010)——IoC篇之加载BeanDefinition:解析和注册BeanDefinition
    Spring5源码分析(009)——IoC篇之加载BeanDefinition:获取 Document 实例
    Spring Boot2(015):JSON
    Spring Boot2(014):国际化 Internationalization
    Spring Boot2(013):日志
    Spring Boot2(012):Profiles
    Spring Boot2(011):外部化配置 Externalized Configuration
    Spring5源码分析(008)——IoC篇之加载BeanDefinition:获取XML的验证模式
    ubuntu 16.04下ssh访问提示错误
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/1760015.html
Copyright © 2020-2023  润新知