国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Working with URLs in JavaScript

Working with URLs in JavaScript

Dec 30, 2024 am 10:11 AM

Working with URLs in JavaScript

Written by Joe Attardi??

URLs are a critical piece of any web app. If your app makes requests to an API, it’s important to craft the correct URLs for these requests. The URL API, supported in all modern browsers, provides a way to parse and manipulate URLs. It provides easy access to the various parts of the URL.

Understanding the parts of a URL

Consider the following URL:

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

This URL is made up of the following components:

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

With modern JavaScript, we can parse URLs and extract these different parts as needed.

Parsing URLs

In older browsers, before the URL API was available, one way that developers parsed URLs was by using an element. This element provides some basic URL parsing. For example, here is a way you could extract the query string from a URL:

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

However, this approach has some disadvantages:

  • It requires a DOM environment, which means it wouldn’t work in an environment such as Node.js
  • It also has no error handling — if an invalid URL is passed to the href attribute, no error is thrown

You could also use a regular expression to parse out the various parts of the URL, but this is tedious and error-prone.

Using the URL API to parse URLs is straightforward. Just pass the URL you want to parse to the URL constructor. If the URL string is valid, you’ll get a URL object back with properties for various parts of the 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

Parsing the query string

You can access the query string of a URL in two ways:

  • The search property, which is a string containing the full query string (including the ? character)
  • The searchParams property, which is a URLSearchParams object

If you’re interested in the value of a particular parameter in the query string, you can use its get method to get the parameter by its name:

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

If there are multiple parameters with the same name, you can use getAll to get an array containing all of the values for that name:

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

Building query strings

Building a query string by hand can be tricky, especially if any query parameters contain special characters that need to be escaped. For example, if a query parameter needs to contain a & character, you’d need to encode it as &. To cover these situations, you need to use the encodeURIComponent function:

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

You can build the query string more safely by using the URLSearchParams object:

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

Advantages of using URLSearchParams include:

  • You don’t have to worry about the & characters separating the parameters
  • You don’t need to URI-encode the parameter values
  • You don’t need to use string concatenation

Iterating over query parameters

Without a URLSearchParams object, it’s a little tricky to iterate over the parameters in a query string. You would need to split strings several times — first into groups of key/value pairs, then again to split up the key and value:

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

If the parameters could contain encoded characters, you’d also need to decode them:

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

Instead, you can use URLSearchParams's entries method to iterate over the key/value pairs:

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

Building a full URL

Here’s a full example of building a URL with a base URL and some query parameters:

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

Checking for valid URLs

You might try using a regular expression to validate a URL, but it’s notoriously difficult to craft a regular expression that fully captures a valid URL string.

Instead, you can reach for the URL API. The URL constructor will throw an error if you give it an invalid URL. You can use this to check if a URL is valid:

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

With newer browsers, this is even easier. There’s a newer URL.canParse static method that performs similar validation with a single line of code. Like the isValidURL function above, it takes a potential URL string and returns true or false depending on the validity of the URL string.

Creating relative URLs

The URL API has a powerful mechanism for resolving relative URLs. Normally, the argument to the URL constructor will throw an error if it’s not a full, valid URL. However, you can specify a second argument that serves as a base from which to build a relative URL. If you use the two-argument approach, the first argument doesn’t have to be a valid URL but the second one does.

Let’s look at a simple case first:

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

The URL constructor takes the base URL of https://example.com and adds the relative path /about, resulting in https://example.com/about.

What about this one:

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

You might expect this to be https://example.com/users/profile, but it actually comes out to https://example.com/profile. This behaves just like a relative link; it takes the parent path segment, which is the root of example.com, and then adds profile.

Let’s look at one more example of using a relative URL. You can also use .. to go back up the path hierarchy:

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

This one comes out to https://example.com/profile. Remember that relative URLs start at the parent path segment. Then, this one has .. in it, which goes up one more path segment.

If you call the URL constructor with a relative URL and specify an invalid or incomplete URL for the base URL, you’ll get an error. You’ll also get an error if you use a relative URL without a full base 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

Working with the window.location object

You might be familiar with the window.location object, which represents the current page’s URL. This object also has properties such as href and pathname, so you might think it’s a URL object. This is a different object, a Location, which has some properties in common with URL, but is also missing some (such as the searchParams property).

Even though it’s not a URL object, you can still use window.location to construct new URL objects. You can pass window.location to the URL constructor to create a new full-blown URL with searchParams and all, based on the current URL, or you can even use it as the base URL when constructing relative URLs:

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

Matching patterns within a URL using URLPattern

Using a URL makes it easy to get the path from a URL. For example, in the URL https://example.com/api/users/123/profile, the path name is /api/users/123/profile. What if we wanted to get just the user ID, 123, from this URL?

As we discussed earlier, it can be difficult to create proper regular expressions to validate and extract parts of a URL.

It’s not available in all browsers just yet, but you can use the URLPattern API to match and extract parts of the URL, matching patterns you specify. This can be particularly useful for things like client-side routing in a single-page application (SPA).

Using the user profile URL as an example, let’s create a URLPattern to get the user ID. We can use a leading : character to denote a named placeholder, which can be used later to match that part of the URL:

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

When you call exec on a URLPattern, it needs a valid URL. It returns a matcher object that contains properties for each of the URL’s parts (protocol, host, pathname, etc.). Each of these properties also has a groups property, which maps placeholder names like :userId to their values within the URL.

If you’re only concerned about matching one part of the URL, such as the path name as we’ve done here, you can specify wildcards in the URL pattern as well. Or, instead of a URL string, you can pass an object containing the parts of the URL you’re interested in matching:

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

The URLPattern API is still not available in all browsers. At the time of writing, it’s not yet supported in Firefox or Safari. You can see the latest browser support information at CanIUse.com.

Summary

The URL API is a versatile interface for constructing, validating, and manipulating URLs in JavaScript. It’s safer and less error-prone to use than manual parsing or regular expressions. By using a URLSearchParams object, you can build a query string without worrying about string concatenation or encoding special characters.

The URLPattern API takes this a step further, supporting wildcards and named placeholders, so you can slice and dice URLs to meet your app’s needs! Further reading:

  • The URL interface (MDN)
  • The URLPattern API (MDN)

Get set up with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.

NPM:

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

Script Tag:

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

3.(Optional) Install plugins for deeper integrations with your stack:

  • Redux middleware
  • ngrx middleware
  • Vuex plugin

Get started now

The above is the detailed content of Working with URLs in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

A JS roundup of higher-order functions beyond map and filter A JS roundup of higher-order functions beyond map and filter Jul 10, 2025 am 11:41 AM

In JavaScript arrays, in addition to map and filter, there are other powerful and infrequently used methods. 1. Reduce can not only sum, but also count, group, flatten arrays, and build new structures; 2. Find and findIndex are used to find individual elements or indexes; 3.some and everything are used to determine whether conditions exist or all meet; 4.sort can be sorted but will change the original array; 5. Pay attention to copying the array when using it to avoid side effects. These methods make the code more concise and efficient.

Filtering an Array of Objects in JavaScript Filtering an Array of Objects in JavaScript Jul 12, 2025 am 03:14 AM

The filter() method in JavaScript is used to create a new array containing all the passing test elements. 1.filter() does not modify the original array, but returns a new array that meets the conditional elements; 2. The basic syntax is array.filter((element)=>{returncondition;}); 3. The object array can be filtered by attribute value, such as filtering users older than 30; 4. Support multi-condition filtering, such as meeting the age and name length conditions at the same time; 5. Can handle dynamic conditions and pass filter parameters into functions to achieve flexible filtering; 6. When using it, be careful to return boolean values ??to avoid returning empty arrays, and combine other methods to achieve complex logic such as string matching.

How to Check if an Array Includes a Value in JavaScript How to Check if an Array Includes a Value in JavaScript Jul 13, 2025 am 02:16 AM

In JavaScript, check whether an array contains a certain value. The most common method is include(), which returns a boolean value and the syntax is array.includes(valueToFind), for example fruits.includes('banana') returns true; if it needs to be compatible with the old environment, use indexOf(), such as numbers.indexOf(20)!==-1 returns true; for objects or complex data, some() method should be used for in-depth comparison, such as users.some(user=>user.id===1) returns true.

The Concept of a Virtual DOM Explained in JavaScript Context The Concept of a Virtual DOM Explained in JavaScript Context Jul 12, 2025 am 03:09 AM

Virtual DOM is a programming concept that optimizes real DOM updates. By creating a tree structure corresponding to the real DOM in memory, it avoids frequent and direct operation of real DOM. Its core principle is: 1. Generate a new virtual DOM when the data changes; 2. Find the smallest difference between the new and old virtual DOMs; 3. Batch update of the real DOM to reduce the overhead of rearrangement and redrawing. In addition, using a unique stable key can improve list comparison efficiency, while some modern frameworks have adopted other technologies to replace virtual DOM.

Error Handling in Async/Await JavaScript Functions Error Handling in Async/Await JavaScript Functions Jul 12, 2025 am 03:17 AM

To handle errors in asynchronous functions, use try/catch, handle them in the call chain, use the .catch() method, and listen for unhandledrejection events. 1. Use try/catch to catch errors is the recommended method, with a clear structure and can handle exceptions in await; 2. Handling errors in the call chain can be centralized logic, which is suitable for multi-step processes; 3. Use .catch() to catch errors after calling async function, which is suitable for Promise combination scenarios; 4. Listen to unhandledrejection events to record unhandled rejections as the last line of defense; the above methods jointly ensure that asynchronous errors are correctly captured and processed.

How to handle time zones in JavaScript? How to handle time zones in JavaScript? Jul 11, 2025 am 02:41 AM

The key to dealing with JavaScript time zone issues is to choose the right method. 1. When using native Date objects, it is recommended to store and transfer in UTC time and convert it to the user's local time zone when displaying; 2. For complex time zone operations, moment-timezone can be used, which supports IANA time zone database and provides convenient formatting and conversion functions; 3. If you need to localize the display time and do not want to introduce third-party libraries, you can use Intl.DateTimeFormat; 4. It is recommended to modern lightweight solution day.js and timezone and utc plug-in, which has a concise API, good performance and supports timezone conversion.

See all articles