3

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?

MrLewk
  • 498
  • 1
  • 6
  • 24

2 Answers2

3

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'));
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • Does not work with pretty urls, assuming you have a get variable hidden example.com/dashboard where dashboard is a get parameter named page – ii iml0sto1 Oct 26 '19 at 15:48
0

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'
salezica
  • 74,081
  • 25
  • 105
  • 166