Quick Tip: Get URL Parameters with JavaScript

3D ad banner ad revenue ad revenues adobe XD Advanced advanced-css-tools advanced-css-tutorials AdvancedCSS AdvancedCSS-hub agency Agile Agile Development Ajax Alex Skill Kit Alexa Alexa skill AlexW Amazon Alexa amazon developer analytics Angelap angular AngularJS Animation anime.js ANN api apollo Appsflyer array methods artificial neural network Async async components automation Avocode AWS AWS Lambda axios b2b b2c baas background background eraser tool Banner banner ad Bannersnack bawmedia bem bitcoin black friday Blogs bootstrap bot browser testing Browsers build process bundler Business business success Canvas & SVG career Career Advancement CDN Chakra UI charting chat app chatbots ChatKit chrome chrome developer tools chrome extension chrome extensions chromium ciphering cli cli tools climate climate action clojure cloud hosting CloudFlare Cloudways cms CNN code challenge ColinI compiler components const assertions constructs content content delivery network context api convoluted neural network create react app cron job cross browser testing cross platform development cross-browser cryptocurrencies CSS CSS Architecture css blur css challenge css framework css frameworks css grid css modules CSS print css rem css typography CSS-in-JS CSS3 css3 transforms cssbattle.dev D3.js data visualization databases debugging decoupled cms deep linking delay Design Design & UX design career design handoff Detox dev environment developer tools DevOps devtools diagnostic analytics digit recognition digital agency digitalocean Discord discounts Docker Docker Containers E-commerce ECMAScript edge computing editor elastic em units employment end-to-end testing energy energy usage Entrepreneur Entrepreneurship environment erasing backgrounds es6 ES6 classes eslint Expo Express FaaS face detection face recognition Feathers Feathers.js figma flatfile framework Frameworks freelancing functional programming functions gatsby generators geolocation gitCS github github API Google Photos GraphCMS graphing graphql Growth Grunt Gulp haskell headless CMS hooks hosting HTML HTML & CSS html preprocessor HTML5 HTML5 Dev Center https://www.sitepoint.com/windows-linux-subsystem-2-windows-terminal IAAS IDE Illustration image optimization immutability ionic IP2Location jade jamesh JavaScript javascript framework javascript frameworks javascript tooling Jest job joelf jQuery jquery get url params jquery string functions jquery4u js js framework JS tooling Keras keycdn lambdatest launch checklist Layout learn-advanced-css learn-modernjs Learn-Node-JS learn-vue Lift linux linux containers location tracking LouisL Managed managed hosting mariap marvel MBaaS mekanism mind map mind mapping mindmapping Mobile mobile attribution Mobile Design modernjs modernjs-hub modernjs-tools modules monday mongodb MTCNN multi-threading natural language processing Navigation navigation library nest Next.js nilsonj node node version manager node-hub Node-JS-Tools Node-JS-Tutorials Node.js nodejs noops npm nvm objects octobercms Offers online publishing PaaS Package Management package manager pause Percy Performance Photography & Imagery Photoshop Photoshop Tutorials & Articles pip portfolio portfolio builders preprocessors prettier print styles Prisma Private Class Fields product design Profitability Programming PubNub Pug Puppeteer Pusher python python job Quasar query strings quick-tip quote builders Raw JavaScript React react components React Hooks React Hooks Form React native reactive Reactive Programming reactive web apps read offline Reat native elements Recurring Payments recursive types RedBox redux rem units remote work remote work tips removing backgrounds resilient Resources responsive REST restful api Review SaaS sampling sass Scss self sencha serverless serverless computing shared hosting sharing state sharpen side project siteground sketch slashdata sleep Software sorting specifications speech recognition speech recognition api sponsored state state management static module bundler StudioWorks Styled Components styling React components survey sustainability svelte sympli Tailwind task runner telegram bots Template engine Testing text to speech Themes Tic Tac Toe Tinder toggle Tolerance tooling tooling anxiety tools Tools & Libraries transformations TypeScript Ubuntu UI UI Design Usability user experience user research UX ux issues vanilla javascript VGGFace2 virtual machine visual testing voice recognition vps vue Vue CLI vue dev environment vue-hub vue-tutorials vue.js vuetify vuex wait WatermelonDB Web Web Design web hosting Web Hosting & Domains Web standards web workers webpack website builders website performance WebSockets windows windows 10 home Windows Subsystem for Linux Windows Terminal wix women women in tech WordPress wordpress themes work workers workflow working remotely workplaces WPEngine WSL WSL2 YellowBox Zeplin

URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more.

In this article, we’ll show you how to parse and manipulate URL parameters using JavaScript.

Getting a URL Parameter

In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.

Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:

const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m

We can then parse the query string's parameters using URLSearchParams:

const urlParams = new URLSearchParams(queryString);

Then we call any of its methods on the result.

For example, URLSearchParams.get() will return the first value associated with the given search parameter:

const product = urlParams.get('product')
console.log(product);
// shirt

const color = urlParams.get('color')
console.log(color);
// blue

const newUser = urlParams.get('newuser')
console.log(newUser);
// empty string

Other Useful Methods

Checking for the Presence of a Parameter

You can use URLSearchParams.has() to check whether a certain parameter exists:

console.log(urlParams.has('product'));
// true

console.log(urlParams.has('paymentmethod'));
// false

Getting All of a Parameter's Values

You can use URLSearchParams.getAll() to return all of the values associated with a particular parameter:

console.log(urlParams.getAll('size'));
// [ 'm' ]

//Programmatically add a second size parameter.
urlParams.append('size', 'xl');

console.log(urlParams.getAll('size'));
// [ 'm', 'xl' ]

Iterating over Parameters

URLSearchParams also provides some familiar Object iterator methods, allowing you iterate over its keys, values and entries:

const
  keys = urlParams.keys(),
  values = urlParams.values(),
  entries = urlParams.entries();

for (const key of keys) console.log(key);
// product, color, newuser, size

for (const value of values) console.log(value);
// shirt, blue, , m

for(const entry of entries) {
  console.log(`${entry[0]}: ${entry[1]}`);
}
// product: shirt
// color: blue
// newuser:
// size: m

Browser Support

Browser support for URLSearchParams is good. At the time of writing, it’s supported in all major browsers.


Data on support for the urlsearchparams feature across the major browsers from caniuse.com

There’s a polyfill available if you have to support legacy browsers such as Internet Explorer. Or, you could follow along with the rest of this tutorial and learn how to roll your own.

Rolling Your Own Query String Parsing Function

Let’s stay with the URL we were using in the previous section:

http://example.com/?product=shirt&color=blue&newuser&size=m

Here’s a function to give you all the URL parameters as a neat object:

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i = 0; i < arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // set parameter name and value (use 'true' if empty)
      var paramName = a[0];
      var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

      // if the paramName ends with square brackets, e.g. colors[] or colors[2]
      if (paramName.match(/[(d+)?]$/)) {

        // create key if it doesn't exist
        var key = paramName.replace(/[(d+)?]/, '');
        if (!obj[key]) obj[key] = [];

        // if it's an indexed array e.g. colors[2]
        if (paramName.match(/[d+]$/)) {
          // get the index value and add the entry at the appropriate position
          var index = /[(d+)]/.exec(paramName)[1];
          obj[key][index] = paramValue;
        } else {
          // otherwise add the value to the end of the array
          obj[key].push(paramValue);
        }
      } else {
        // we're dealing with a string
        if (!obj[paramName]) {
          // if it doesn't exist, create property
          obj[paramName] = paramValue;
        } else if (obj[paramName] && typeof obj[paramName] === 'string'){
          // if property does exist and it's a string, convert it to an array
          obj[paramName] = [obj[paramName]];
          obj[paramName].push(paramValue);
        } else {
          // otherwise add the property
          obj[paramName].push(paramValue);
        }
      }
    }
  }

  return obj;
}

You’ll see how this works soon, but first, here are some usage examples:

getAllUrlParams().product; // 'shirt'
getAllUrlParams().color; // 'blue'
getAllUrlParams().newuser; // true
getAllUrlParams().nonexistent; // undefined
getAllUrlParams('http://test.com/?a=abc').a; // 'abc'

And here's a demo for you to play around with.

See the Pen rQGWpP by SitePoint (@SitePoint) on CodePen.

Let's get started!

Getting URL Parameters

Let's say you have the following url:

http://example.com/?product=shirt&color=blue&newuser&size=m

Here's a function to give you all the URL parameters as a neat object:

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/[d*]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

The post Quick Tip: Get URL Parameters with JavaScript appeared first on SitePoint.

Original Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.