URL: search property

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

Note: This feature is available in Web Workers.

The search property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".

This property can be set to change the query string of the URL. When setting, a single "?" prefix is added to the provided value, if not already present. Setting it to "" removes the query string.

The query is percent-encoded when setting but not percent-decoded when reading.

Modern browsers provide the URL.searchParams property to make it easy to parse out the parameters from the query string.

Value

A string.

Examples

Basic usage

js
const url = new url(/Education?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FURL%2F%2522https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FURL%2Fsearch%3Fq%3D123%2522%2C);
console.log(url.search); // Logs "?q=123"

Interaction with searchParams

The URL.searchParams property exposes the search string as a URLSearchParams object. When updating this URLSearchParams, the URL's search is updated with its serialization. However, URL.search encodes a subset of characters that URLSearchParams does, and encodes spaces as %20 instead of +. This may cause some surprising interactions—if you update searchParams, even with the same values, the URL may be serialized differently.

js
const url = new url("/Education?url=https%3A%2F%2Fexample.com%2F%3Fa%3Db%2520~");
console.log(url.href); // "https://example.com/?a=b%20~"
console.log(url.searchParams.toString()); // "a=b+%7E"
// This should be a no-op, but it changes the URL's query to the
// serialization of its searchParams
url.searchParams.sort();
console.log(url.href); // "https://example.com/?a=b+%7E"

const url2 = new url("/Education?url=https%3A%2F%2Fexample.com%2F%3Fsearch%3D1234%26amp%3Bparam%3Dmy%2520param");
console.log(url2.search); // "?search=1234&param=my%20param"
url2.searchParams.delete("search");
console.log(url2.search); // "?param=my+param"

Specifications

Specification
URL
# dom-url-search

Browser compatibility

See also

  • The URL interface it belongs to.