简体   繁体   中英

Getting query string parameters from clean/SEO friendly URLs with JavaScript

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?

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'));

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM