Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save anthonyalvarez/62f69b14a7512a76398cf831f23eba09 to your computer and use it in GitHub Desktop.

Select an option

Save anthonyalvarez/62f69b14a7512a76398cf831f23eba09 to your computer and use it in GitHub Desktop.
JavaScript URLSearchParams, Constructing Query Strings

JavaScript URLSearchParams, Constructing Query Strings

The very convenient URLSearchParams object within JavaScript lets you easily work with query strings - it provides methods to add, remove and retrieve key value pairs and most importantly, extract an encoded query string for further use. This object is a relief for traditional JavaScript developers who know the pain of using regular expressions to extract query string data or manual string construction to create a query string. URLSearchParams does all this for you through its very helpful methods.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>URLSearchParams - JavaScript</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <h1>URLSearchParams</h1>
  <script>
    const queryStr = 'name=Dom&age=45&occupation=Software+Developer'
    const usp = new URLSearchParams(queryStr)
    const myName = usp.get('name')

    console.log(`Value for 'name' : ${myName}`)
    usp.set('name', 'Jeff')
    usp.set('youtube', 'dcode')

    for (const [key, value] of usp) {
      console.log(`${key} => ${value}`)
    }

    console.log(usp.toString())
  </script>
</body>

</html>

References

  1. YouTube Video

  2. MDN - URLSearchParams

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment