Accès et modification des valeurs de chaîne de requête à l'aide d'URLSearchParams
LeProtocole HTTPpermet de faire la demande à une page Web avec une chaîne de requête.
Comme ça:
https://test.com/?name=roger
https://test.com/hello?name=rogerIn this case we have a single query parameter, named name
, with the value roger
.
You can have multiple parameters, like this:
https://test.com/hello?name=roger&age=20The parameters passed as a query string are normally used server-side, to generate a proper response. Here’s how you can access query parameters using Node.js.
To access the value of the query inside the browser, using JavaScript, we have a special API called URLSearchParam, supported by all modern browsers
Here is how we can use it:
const params = new URLSearchParams(window.location.search)
Note: don’t pass the full URL as a parameter to URLSearchParams()
, but only the query string part of the URL, which you access using window.location.search
.
In the case of:
https://test.com/hello?name=rogerwindow.location.search
is equal to the string ?name=roger
.
Now that you have the params
object, you can query it.
You can check if a parameter was passed:
params.has('test')
You can get the value of a parameter:
params.get('test')
You can iterate over all the parameters, using for..of
:
const params = new URLSearchParams(window.location.search)
for (const param of params) {
console.log(param)
}
A parameter can have more than one value.
In this case, we pass the same parameter name multiple times, like this:
https://test.com/hello?name=roger&name=flavioWe have no way to detect if a parameters is passed more than once. If we use params.get('name')
, we’ll only get the first value back.
We can sue params.getAll('name')
to get back an array with all the values passed.
In addition to has()
, get()
and getAll()
, the URLSearchParams
API offers several other methods that we can use to loop through the parameters:
forEach()
iterates over the paramters
entries()
returns an iterator containing the parameters key/values
keys()
returns an iterator containing the parameters keys
values()
returns an iterator containing the parameters values
Other methods to alter the parameters, for use in other JavaScript running in the page (they do not change the URL):
append()
to append a new parameter to the object
delete()
to delete an existing parameter
set()
to set the value of a parameter
We also have sort()
to sort parameters by key value, and we have the toString()
method to generate a query string from the values.
We can use append()
/ set()
/ delete()
to edit the query string, and generate a new one with toString()
.
Download my free JavaScript Beginner's Handbook
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts