Let's talk about the mutual conversion methods of URL parameters and JS objects

PHPz
Release: 2023-04-06 11:40:03
Original
2411 people have browsed it

In the process of front-end development, we often encounter situations where URL parameters and objects in JavaScript need to be converted to each other. For example, when we need to use URL query parameters to control the behavior of the page, we need to parse the URL parameters into objects in JavaScript for operation; or when we need to pass some data on the page to the server, We need to convert the object into URL parameters for request.

This article will introduce the mutual conversion method between URL parameters and objects in JavaScript, and provide some practical code examples.

  1. Convert URL parameters into JavaScript objects

For converting URL parameters into JavaScript objects, we first need to parse the URL parameters into a string, and then parse it into an object.

1.1 Parse URL parameters as strings

We can use the window.location.search method in JavaScript to get the query parameters in the current page URL. The string returned by this method contains everything after ? in the URL, but does not include # and the anchor parameters that follow it.

The following is a sample code to get the query parameters of the current page URL:

const queryString = window.location.search;
Copy after login

If we want to get the query parameters in the URL of other pages, we can use new URL(urlString).search method, just pass in the URL that needs to be parsed. For example:

const url = "https://example.com/page/?name=John&age=20";
const queryString = new URL(url).search; // 返回"?name=John&age=20"
Copy after login

1.2 Parse query parameters into objects

Next, we need to parse the query parameter string into an object in JavaScript. We can manually write a parsing function, but it is recommended to use the third-party library query-string, which provides some convenient parsing methods.

First, we need to use npm or yarn to add the query-string library to the project:

npm install query-string --save
# 或者
yarn add query-string
Copy after login

Then we can use the ## provided in the library #parse method, converts the string of URL query parameters into objects. For example:

import queryString from 'query-string';

const values = queryString.parse(queryString);
Copy after login
Among them,

values is a parsed object. For example, if queryString is "?name=John&age=20", then values is {name: "John", age: "20 "}.

    Convert JavaScript objects into URL parameters
When we need to convert objects in JavaScript into URL parameters, we need to convert each key-value pair in the object Concatenate to form a string of URL query parameters.

2.1 Convert the object into a string

We can manually write a conversion function, first traverse all the key-value pairs in the object, convert them into "key=value" format, and then use "&" symbol to connect. For example:

function toQueryString(obj) {
  const parts = [];
  
  for (const [key, value] of Object.entries(obj)) {
    parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
  }
  
  return parts.join('&');
}

const values = {
  name: "John",
  age: 20
};

const queryString = toQueryString(values);
// 返回 "name=John&age=20"
Copy after login
Note that we use the

encodeURIComponent method when encoding each key-value pair into a string. This method can encode special characters in the string to prevent illegal URL query parameters. For example, if the key-value pair contains a special character "?", it will be converted to an encoded string like "?".

2.2 Add a string to the URL

Now that we have converted the JavaScript object into a string, the next task is to add it to the URL.

If we want to directly modify the query parameters in the current window URL, we can use the

window.location.search property to modify it. For example:

const queryString = toQueryString(values);
window.location.search = queryString;
Copy after login
If we want to construct a new URL and jump, we can use the

window.location.href attribute or window.location.replace method. For example:

const queryString = toQueryString(values);
const url = `https://example.com/page/?${queryString}`;
window.location.href = url;
// 或者
window.location.replace(url);
Copy after login
Note that here we need to splice the complete URL ourselves instead of simply using

window.location.search. Because the search attribute will only return the query parameter part of the current URL, we also need to manually splice the host name, path name, anchor parameters, etc.

Summary

This article introduces the mutual conversion method of URL parameters and objects in JavaScript. We can get the query parameters in the URL through the

location.search method and use the query-string library to parse the query parameter string into a JavaScript object. Conversely, we can also manually write a helper function to convert the JavaScript object into a query parameter string and add it to the URL.

The above operations are very simple, but they are often used in actual front-end development. I hope it can help readers.

The above is the detailed content of Let's talk about the mutual conversion methods of URL parameters and JS objects. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template