js 获取 url 地址参数

思路:
  • 通过location的search就可以获取到url中问号后面的值。
  • 字符串过滤到问号
  • 通过split方法分割参数集合
  • 循环赋值
  • 匹配对应的参数值
  • 返回值
function getUrlParams(name) { // 不传name返回所有值,否则返回对应值
    var url = window.location.search;
    if (url.indexOf('?') == 1) { return false; }
    url = url.substr(1);
    url = url.split('&');
    var name = name || '';
    var nameres;
    // 获取全部参数及其值
    for(var i=0;i<url.length;i++) {
        var info = url[i].split('=');
        var obj = {};
        obj[info[0]] = decodeURI(info[1]);
        url[i] = obj;
    }
    // 如果传入一个参数名称,就匹配其值
    if (name) {
        for(var i=0;i<url.length;i++) {
            for (const key in url[i]) {
                if (key == name) {
                    nameres = url[i][key];
                }
            }
        }
    } else {
        nameres = url;
    }
    // 返回结果
    return nameres;
}
实例
const url = 'http://www.abc.com/test.php?id=1&from=index';
var res = getUrlParams();
var res1 = getUrlParams('id');
console.log(res); //  [{id: "1"}, {from: "index"}]
console.log(res1); // 1
其他
window.location:
属性 描述
hash 设置或获取 href 属性中在井号“#”后面的分段。
host 设置或获取 location 或 URL 的 hostname 和 port 号码。
hostname 设置或获取 location 或 URL 的主机名称部分。
href 设置或获取整个 URL 为字符串。
pathname 设置或获取对象指定的文件名或路径。
port 设置或获取与 URL 关联的端口号码。
protocol 设置或获取 URL 的协议部分。
search 设置或获取 href 属性中跟在问号后面的部分。

eg:
http://localhost:8086/topic/index?topicId=361

  • console.log(window.location.host):输出:http:localhost:8086

  • console.log(window.location.href);:输出:http://localhost:8086/topic/index?topicId=361

  • console.log(window.location.pathname);:输出:/topic/index

  • console.log(window.location.port):输出:8086

  • console.log(window.location.protocol);:输出: http:

  • console.log(window.location.search);:输出:?topicId=361

参考:

  1. https://zhuanlan.zhihu.com/p/72581171
  2. https://www.jianshu.com/p/0efc0b5ab157
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容