URLSearchParams.set()

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

 

The set() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.

Syntax

URLSearchParams.set(name, value)

Parameters

name
The name of the parameter to set.
value 
The value of the parameter to set.

Returns

Void

Example

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

//Add a third parameter.
params.set('baz', 3);

Example2

This is a real-life example demonstrating how to create a URL and set some search parameters.

You can copy&paste the example in your [Scratchpad]

  • line#26: uncomment to dump the search parameters to the console.
  • line#28: Will dump the generated object and it's string representation to the console.
  • line#29: Will automatically try to open a new window/tab with the generated url (when uncommented).
  • See also Issue 242 on gskinner/regexr @github about a bug in this function...
'use strict'

function genURL(rExp, aText, bDebug=false){
    let theURL

    theURL= new URL('https://regexr.com')
    theURL.searchParams.set( 'expression', rExp.toString() )
    theURL.searchParams.set( 'tool', 'replace' )
    theURL.searchParams.set( 'input', '' )
    theURL.searchParams.set( 'text', aText.join('\n') )
    if( bDebug ){
        // Display the key/value pairs
        for(var pair of theURL.searchParams.entries()) {
            console.debug(pair[0] + ' = \'' + pair[1] + '\''); 
        }
        console.debug(theURL)
    } 
    return theURL
}
var url = genURL(
    /(^\s*\/\/.*|\s*[^:]\/\/.*)/g
    ,[
        "// eslint-disable-next-line no-unused-vars",
        "lockPref(	'keyword.URL',\t\t'https://duckduckgo.com/html/?q=!+'	)\t// test"
    ]
//     , true
)
console.info( url, url.toString() )
// window.open( url, 'regex_site' )

Specifications

Specification Status Comment
URL
The definition of 'set()' in that specification.
Living Standard Initial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 49.0 (Yes) No support (Yes) ?
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support 49.0 (Yes) No support (Yes) ? 49.0

Document Tags and Contributors

 Contributors to this page: TriMoon, chrisdavidmills, triblondon, rolfedh, jpmedley
 Last updated by: TriMoon,