JavaScript 获取 URL 参数及 Location 对象详解

作者:小括号

时间:2026-10-22

浏览:599

本文详解JavaScript中window.location对象的常用属性与方法,包括assign、replace、reload及toString的具体用法。重点讲解如何利用正则表达式从URL查询字符串中提取指定参数值,提供完整的getUrlParam函数实现及调用示例,帮助开发者快速掌握前端地址栏数据处理技巧。

文章目录

Location 对象核心属性与方法

假设当前访问的网页地址为:http://127.0.0.1:8082/prosperleedir/index.html?id=6666&name=prosper#prosper


Location{

 assign:ƒ (),         // 加载新的文档。

 hash:"#prosper",       // 设置或返回从井号 (#) 开始的 URL(锚)。

 host:"127.0.0.1:8082",    // 设置或返回主机名和当前 URL 的端口号。

 hostname:"127.0.0.1",     // 设置或返回当前 URL 的主机名。

 href:"http://127.0.0.1:8082/prosperleedir/index.html?id=6666&name=prosper#prosper",   // 设置或返回完整的 URL。

 origin:"http://127.0.0.1:8082",    // 返回当前 URL 的协议和主机名和当前 URL 的端口号。

 pathname:"/prosperleedir/index.html",      // 设置或返回当前 URL 的路径部分。

 port:"8082",       // 设置或返回当前 URL 的端口号。

 protocol:"http:",      // 设置或返回当前 URL 的协议。

 reload:ƒ reload(),      // 重新加载当前文档。

 replace:ƒ (),       // 用新的文档替换当前文档。

 search:"?id=6666&name=prosper",     // 设置或返回从问号 (?) 开始的 URL(查询部分)。

 toString:ƒ toString(),      // 返回完整的 URL。

}

调用该方法以加载新的文档。


window.location.assign(http://www.baidu.com);

使用新文档替换当前文档。


window.location.replace(http://www.baidu.com);

重新加载当前文档。

若该方法未指定参数或参数为 false,它将使用 HTTP 头 If-Modified-Since 检测服务器端文档是否发生更改。若文档已更新,reload() 会重新下载该文档;若未更新,则从缓存中加载。此行为等同于用户点击浏览器刷新按钮。

若将参数设置为 true,无论文档最后修改时间如何,均会绕过缓存并从服务器重新下载。这等同于用户在点击刷新按钮时按住 Shift 键的效果。


window.location.reload(true);

window.location.reload(false);

返回完整的 URL 字符串。


console.log(window.location.toString());

Location 对象核心属性与方法

正则表达式提取 URL 参数实现


/**

     * [getUrlParam 获取地址栏传参]

     * @param {[String]} paramname [参数名]

     * @return {[String]}      [参数值]

     */

    function getUrlParam(paramname) {

           

      var reg = new RegExp("(^|&)" + paramname + "=([^&]*)(&|$)");

 

      // 查询匹配 substr(1)删除? match()匹配

      var s = window.location.search.substr(1).match(reg);

 

      if (s != null) {

 

        return unescape(s[2]); // unescape() 函数可对通过 escape() 编码的字符串进行解码。

 

      }

 

      return null;

 

    }

 

    // ?id=6666&name=prosper

    getUrlParam('id'); // s的输出为["id=6666&","","6666","&"]

    getUrlParam('name'); // s的输出为["name=prosper","&","prosper",""]

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章