Location对象

location对象概述

location对象提供了当前文档URL的信息和操作方法。

基本属性

// 假设当前URL: https://www.db-w.cn:443/path/page?id=1#section

console.log(location.href);      // 完整URL
console.log(location.protocol);  // "https:"
console.log(location.host);      // "www.db-w.cn:443"
console.log(location.hostname);  // "www.db-w.cn"
console.log(location.port);      // "443"
console.log(location.pathname);  // "/path/page"
console.log(location.search);    // "?id=1"
console.log(location.hash);      // "#section"
console.log(location.origin);    // "https://www.db-w.cn"

URL结构图示

https://www.db-w.cn:443/path/page?id=1#section
\_____/   \________/ \_/ \_______/ \___/ \______/
   |         |        |      |       |      |
protocol  hostname  port pathname search  hash
   |_____________________|  
            |
          host
   |___________________________________|
                    |
                 origin
   |_____________________________________________|
                          |
                        href

属性修改

// 修改属性会触发页面跳转

// 跳转到新URL
location.href = "https://db-w.cn";

// 修改hash(不刷新页面)
location.hash = "#top";

// 修改search(刷新页面)
location.search = "?page=2";

// 修改pathname(刷新页面)
location.pathname = "/new-page";

URL解析

解析URL的各个组成部分。

使用location属性

// 获取协议
const isHttps = location.protocol === "https:";

// 获取域名
const domain = location.hostname;

// 获取路径
const path = location.pathname;

// 判断是否在根路径
const isRoot = location.pathname === "/";

// 判断端口
const isDefaultPort = location.port === "" || 
    (location.protocol === "http:" && location.port === "80") ||
    (location.protocol === "https:" && location.port === "443");

使用URL对象

// 创建URL对象
const url = new URL("https://www.db-w.cn/path?page=1#top");

console.log(url.href);      // 完整URL
console.log(url.protocol);  // "https:"
console.log(url.host);      // "www.db-w.cn"
console.log(url.hostname);  // "www.db-w.cn"
console.log(url.port);      // ""
console.log(url.pathname);  // "/path"
console.log(url.search);    // "?page=1"
console.log(url.hash);      // "#top"
console.log(url.origin);    // "https://www.db-w.cn"

// 使用当前URL
const currentUrl = new URL(location.href);

URL解析函数

function parseUrl(urlString) {
    const url = new URL(urlString);
    
    return {
        href: url.href,
        protocol: url.protocol,
        host: url.host,
        hostname: url.hostname,
        port: url.port,
        pathname: url.pathname,
        search: url.search,
        hash: url.hash,
        origin: url.origin
    };
}

const parsed = parseUrl("https://db-w.cn:8080/api/users?id=1");
console.log(parsed);

查询字符串

处理URL中的查询参数。

解析查询字符串

// 手动解析
function parseQueryString(queryString) {
    const params = {};
    const search = queryString.substring(1);  // 去掉?
    
    if (!search) return params;
    
    search.split("&").forEach(pair => {
        const [key, value] = pair.split("=");
        params[decodeURIComponent(key)] = decodeURIComponent(value || "");
    });
    
    return params;
}

const params = parseQueryString("?name=东巴文&url=db-w.cn");
console.log(params);  // { name: "东巴文", url: "db-w.cn" }

构建查询字符串

function buildQueryString(params) {
    return Object.entries(params)
        .map(([key, value]) => 
            `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        )
        .join("&");
}

const queryString = buildQueryString({
    name: "东巴文",
    page: 1,
    size: 10
});
console.log(queryString);  // "name=东巴文&page=1&size=10"

获取当前页面参数

// 使用location.search
const searchParams = parseQueryString(location.search);
console.log(searchParams);

// 直接使用URL对象
const url = new URL(location.href);
const id = url.searchParams.get("id");
const page = url.searchParams.get("page");
console.log(id, page);

URL操作

使用URLSearchParams处理查询参数。

URLSearchParams基本用法

// 创建URLSearchParams
const params = new URLSearchParams();
params.append("name", "东巴文");
params.append("page", "1");
console.log(params.toString());  // "name=东巴文&page=1"

// 从查询字符串创建
const params2 = new URLSearchParams("?name=东巴文&page=1");

// 从对象创建
const params3 = new URLSearchParams({
    name: "东巴文",
    page: 1
});

URLSearchParams方法

const params = new URLSearchParams("?name=东巴文&page=1&size=10");

// 获取参数
console.log(params.get("name"));      // "东巴文"
console.log(params.get("unknown"));   // null

// 获取所有同名参数
params.append("tag", "js");
params.append("tag", "css");
console.log(params.getAll("tag"));    // ["js", "css"]

// 检查参数是否存在
console.log(params.has("name"));      // true
console.log(params.has("unknown"));   // false

// 设置参数
params.set("page", "2");

// 添加参数
params.append("sort", "desc");

// 删除参数
params.delete("size");

// 排序
params.sort();

// 遍历
for (const [key, value] of params) {
    console.log(key, value);
}

// 转换为字符串
console.log(params.toString());

URLSearchParams与URL配合

const url = new URL("https://db-w.cn/search");

// 操作查询参数
url.searchParams.set("q", "JavaScript");
url.searchParams.set("page", "1");
url.searchParams.append("tag", "frontend");

console.log(url.href);
// "https://db-w.cn/search?q=JavaScript&page=1&tag=frontend"

// 获取参数
const q = url.searchParams.get("q");
console.log(q);  // "JavaScript"

页面跳转

使用location对象进行页面导航。

跳转方法

// 跳转到新URL(产生历史记录)
location.assign("https://db-w.cn");

// 直接设置href(与assign相同)
location.href = "https://db-w.cn";

// 替换当前URL(不产生历史记录)
location.replace("https://db-w.cn");

// 重新加载页面
location.reload();         // 从缓存加载
location.reload(true);     // 从服务器加载(强制刷新)

方法对比

方法 产生历史记录 可后退 说明
assign() 跳转到新页面
href = url 与assign相同
replace() 替换当前页面
reload() - - 刷新当前页面

跳转示例

// 登录后跳转
function loginSuccess() {
    const returnUrl = new URLSearchParams(location.search).get("return") || "/";
    location.href = returnUrl;
}

// 登出后替换页面
function logout() {
    clearAuth();
    location.replace("/login");
}

// 条件跳转
if (!isAuthenticated()) {
    location.href = "/login?return=" + encodeURIComponent(location.pathname);
}

// 延迟跳转
setTimeout(() => {
    location.href = "/dashboard";
}, 3000);

URLSearchParams

深入使用URLSearchParams API。

实用方法

const params = new URLSearchParams();

// 批量设置
const data = {
    name: "东巴文",
    email: "info@db-w.cn",
    page: 1
};

Object.entries(data).forEach(([key, value]) => {
    params.set(key, value);
});

// 转换为对象
const obj = Object.fromEntries(params);
console.log(obj);

// 转换为数组
const arr = Array.from(params);
console.log(arr);  // [["name", "东巴文"], ...]

// 遍历键
for (const key of params.keys()) {
    console.log(key);
}

// 遍历值
for (const value of params.values()) {
    console.log(value);
}

// 遍历键值对
for (const [key, value] of params.entries()) {
    console.log(key, value);
}

编码处理

// URLSearchParams自动处理编码
const params = new URLSearchParams();
params.set("name", "东巴文 中文");
params.set("url", "https://db-w.cn/path?query=value");

console.log(params.toString());
// "name=东巴文+中文&url=https%3A%2F%2Fdb-w.cn%2Fpath%3Fquery%3Dvalue"

// 手动编码
const encoded = encodeURIComponent("东巴文 中文");
console.log(encoded);  // "%E4%B8%9C%E5%B7%B4%E6%96%87%20%E4%B8%AD%E6%96%87"

const decoded = decodeURIComponent(encoded);
console.log(decoded);  // "东巴文 中文"

实际应用

// 构建API请求URL
function buildApiUrl(baseUrl, params) {
    const url = new URL(baseUrl);
    Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
            url.searchParams.set(key, value);
        }
    });
    return url.toString();
}

const apiUrl = buildApiUrl("/api/users", {
    page: 1,
    size: 10,
    sort: "name",
    order: "asc"
});
console.log(apiUrl);

// 解析当前页面参数
function getCurrentParams() {
    return Object.fromEntries(
        new URLSearchParams(location.search)
    );
}

// 更新URL参数(不刷新页面)
function updateUrlParams(params) {
    const url = new URL(location.href);
    Object.entries(params).forEach(([key, value]) => {
        if (value === null || value === undefined) {
            url.searchParams.delete(key);
        } else {
            url.searchParams.set(key, value);
        }
    });
    history.pushState({}, "", url);
}

// 使用
updateUrlParams({ page: 2, sort: "date" });

下一步

掌握了Location对象后,让我们继续学习:

  1. History对象 - 学习历史记录管理
  2. 其他BOM对象 - 学习Navigator和Screen
  3. 客户端存储 - 学习Cookie和Storage

东巴文(db-w.cn) - 让编程学习更简单

🎯 东巴文寄语:location对象是操作URL的核心API,掌握URL解析、查询字符串处理和页面跳转是前端开发的基本功。在 db-w.cn,我们帮你轻松掌握URL操作!