URLSearchParams
The interface defines some practical methods to process URL query strings.
An implemented URLSearchParams
object can be used directly in the for...of
structure. For example, the following two lines are equal:
for (const [key, value] of mySearchParams) {}
for (const [key, value] of mySearchParams.entries()) {}
Note: This feature is available in Web Worker .
Constructor
Return an URLSearchParams
object.
method
The interface does not inherit any properties.
Insert a specified key/value pair as a new search parameter.
Delete the specified search parameter and its corresponding value from the search parameter list.
Return an iterator
object that can traverse all key/value pairs.
Get the first value of the specified search parameter.
Get all the values of the specified search parameter, and the return is an array.
Returns Boolean
whether there is this search parameter.
Return iterator
this object contains all the key names of key/value pairs.
Set a new value of a search parameter. If there are multiple values, all other values will be deleted.
Sort by key name.
Returns a string composed of search parameters, which can be used directly on the URL.
Return iterator
this object contains all the values of the key/value pair.
Example
var paramsString = "q=URLUtils.searchParams&topic=api"
var searchParams = new URLSearchParams(paramsString);
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
Gotchas
URLSearchParams
The constructor will not resolve the full URL, but if there is a string starting position ?
, then will be removed.
var paramsString1 = "http://example.com/search?query=%40";
var searchParams1 = new URLSearchParams(paramsString1);
searchParams1.has("query"); // false
searchParams1.has("http://example.com/search?query"); // true
searchParams1.get("query"); // null
searchParams1.get("http://example.com/search?query"); // "@" (equivalent to decodeURIComponent('%40'))
var paramsString2 = "?query=value";
var searchParams2 = new URLSearchParams(paramsString2);
searchParams2.has("query"); // true
var url = new URL("http://example.com/search?query=%40");
var searchParams3 = new URLSearchParams(url.search);
searchParams3.has("query") // true