在JavaScript中使用URL API(js import url)

URL是Web应用的关键部分。所有现代浏览器都支持URLAPI,它提供了一种解析和操作URL的方法。提供了对URL各个部分的访问。

了解URL的组成部分

考虑以下URL:

https://example.com/api/search?query=foo&sort=asc#results

URL由以下组件组成:

  • Protocol:https
  • Host:example.com
  • Path name:/api/search
  • Query string:?query=foo&sort=asc
  • Hash:#results

使用现代JavaScript,我们可以解析URL并根据需要提取这些不同的部分。

解析URL

URLAPI可用之前,开发人员解析URL的一种方法是使用 元素。这个元素提供了一些基本的URL解析。例如,这里有一种方法可以从URL中查询字符串:

function getQueryString(url) {
  const link = document.createElement('a');
  link.href = url;
  return url.search;
}

然而,这种方法有一些缺点:

您也可以使用正则表达式来解析URL的各个部分,但这很繁琐且容易出错。

使用URLAPI来解析URL非常简单。只需将您想要解析的URL传递给URL构造函数。如果URL字符串是有效的,您将返回一个URL对象,其中包含URL各个部分的属性:

const url = new URL('https://example.com/api/search?query=foobar');
console.log(url.host); // example.com
console.log(url.pathname); // /api/search
console.log(url.search); // ?query=foobar

解析查询字符串

您可以通过两种方式访问URL的字符串:

如果你对查询字符串中某个特定参数的值感兴趣,你可以使用它的get方法获取该参数:

const url = new URL('https://example.com/api/search?query=foobar&maxResults=10');
console.log(url.searchParams.get('query'); // foobar
console.log(url.searchParams.get('maxResults'); // 10

如果有多个参数具有相同的名称,可以使用getAll获取一个所有包含该名称的数组:

const url = new URL('https://example.com/api/search?tag=tag1&tag=tag2&tag=tag3');
console.log(url.searchParams.getAll('tag')); // ['tag1', 'tag2', 'tag3']

生成查询字符串

手动构建查询字符串可能比较棘手,尤其是当查询参数包含需要转义的特殊字符时。例如,如果查询参数包含一个特殊字符,则需要将其编码为%26 。为了解决这些问题,你需要使用encodeURIComponent函数:

let queryString = 'foo=bar';
queryString += '&baz=qux';
queryString += '&tag=' + encodeURIComponent('one&two');
console.log(queryString); // foo=bar&baz=qux&tag=one%26two

您可以使用URLSearchParams对象更安全地构建查询字符串:

const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('baz', 'qux');
params.append('tag', 'one&two');
console.log(params.toString()); // foo=bar&baz=qux&tag=one%26two

使用URLSearchParams的优点包括:

遍历查询参数

如果没有URLSearchParams对象,那么在字符串中遍历参数就有点棘手。你需要多次拆分字符串。

function listQueryParams(queryString) {
  queryString.split('&').forEach(param => {
    const [key, value] = param.split('=');
    console.log(`${key}: ${value}`);
  });
}

如果参数包含编码字符,则还需要对它们进行解码:

function listQueryParams(queryString) {
  queryString.split('&').forEach(param => {
    const [key, value] = param.split('=');
    console.log(`${key}: ${decodeURIComponent(value)}`);
  });
}

相反,您可以使用URLSearchParamsentries方法来遍历键/值对:

function listQueryParams(queryString) {
  const params = new URLSearchParams(queryString);
  params.entries().forEach(([key, value]) => console.log(`${key}: ${value}`));
}

创建完整的URL

下面是一个使用基本URL参数构建URL的完整示例:

const url = new URL('https://example.com/api/search');
url.searchParams.append('query', 'test');
url.searchParams.append('tag', 'tag1');
url.searchParams.append('tag', 'tag2');

// https://example.com/api/search?query=test&tag=tag1&tag=tag2
console.log(url.toString());

检查有效的URL

您可以使用URLAPI。如果你给它一个无效的URL,URL构造函数将抛出一个错误。

function isValidURL(url) {
  try {
    new URL(url);
    return true;
  } catch (error) {
    return false;
  }
}

使用较新的浏览器,这甚至更容易。新的URL.canParse静态方法,与上面的isValidURL函数类似。它接受一个URL字符串,并根据URL字符串的有效性,返回truefalse

创建相对URL

URLAPI有一个强大的机制来解析相对URL。通常,如果URL构造函数的参数不是完整、有效的URL,则会抛出错误。但是,您可以指定第二个参数,作为构建相对URL的基础。第一个参数不必是有效的URL,但第二个参数必须是有效的URL。

我们先来看一个简单的案例:

new URL('/about', 'https://example.com').href;

URL构造函数采用https://example.com的基URL,并添加相对路径/about ,得到https://example.com/about

这个呢?

new URL('profile', 'https://example.com/users').href;

您可能认为这是
https://example.com/users/profile
,但实际上它是
https://example.com/profile
。它的行为就像一个相对链接; 它采用父路径段,即example的根.com ,然后添加profile

在 window.location工作

new URL('/profile', window.location).href;

使用URLPattern匹配URL中的模式

使用URL可以很容易地从URL获取路径。例如,在URL
https://example.com/api/users/123/profile
中,路径名为 /API/users/123/profile 。如果我们只想从这个URL中获取用户ID 123 呢?

const pattern = new URLPattern('https://example.com/api/users/:userId/profile');
const matcher = pattern.exec('https://example.com/api/users/123/profile');
console.log(matcher.pathname.groups.userId); // 123

当您在URLPattern上调用exec时,它需要一个有效的URL。它返回一个匹配器对象,其中包含URL的每个部分( 协议主机路径名 等)的属性。这些属性中的每一个都有一个groups属性,它将占位符名称(如 :userId )映射到URL中的值。

URLPatternAPI仍然不能在所有浏览器中使用。在撰写本文时,Firefox或Safari还不支持它。您可以在CanIUse.com上查看最新的浏览器支持信息。

原文链接:,转发请注明来源!