skip to Main Content

I’ve recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.

Previously I had been using this function:

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
        return pair[1];
    }
}
return (false);
}

Which worked fine on things like this as you could just call getQueryVariable("image") and return “awesome.jpg”.

I’ve been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:

var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;

In an attempt to get the array index number of the “page” parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)

JavaScript isn’t my main language, so I’m not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.

Any pointers?

2

Answers


  1. This can be done formally using a library such as router.js, but I would go for simple string manipulation:

    const parts = '/users/bob'.split('/')
    const name = parts[parts.length - 1] // 'bob'
    
    Login or Signup to reply.
  2. How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.

    function getPathVariable(variable) {
      var path = location.pathname;
    
      // just for the demo, lets pretend the path is this...
      path = '/images/awesome.jpg/page/about';
      // ^-- take this line out for your own version.
    
      var parts = path.substr(1).split('/'), value;
    
      while(parts.length) {
        if (parts.shift() === variable) value = parts.shift();
        else parts.shift();
      }
    
      return value;
    }
    
    console.log(getPathVariable('page'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search