Getting query string parameters from clean/SEO friendly URLs with JavaScript - 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'

Related

Javascript get URL parameter that starts with a specific string

With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. Is there a regex that would return this, or an option to get all url parameters, then loop through the results?
Example: www.domain.com/?Loc-chicago=test
If two are present in the url, I need to get both, such as:
www.domain.com/?Loc-chicago=test&Loc-seattle=test2
You can use window.location.search to get all parameters after (and including ?) from url. Then it's just a matter of looping through each parameter to check if it match.
Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array:
var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})
Use URLSearchparams
The URLSearchParams interface defines utility methods to work with the
query string of a URL.
var url = new URL("http://" + "www.domain.com/?Loc-chicago=test&NotLoc=test1&Loc-seattle=test2");
var paramsString = url.search;
var searchParams = new URLSearchParams(paramsString);
for (var key of searchParams.keys()) {
if (key.startsWith("Loc-")) {
console.log(key, searchParams.get(key));
}
}
Here is a function you can use that accepts a parameter for what you are looking for the parameter to start with:
function getUrlParameters(var matchVal) {
var vars = [];
var qstring = window.location.search;
if (qstring) {
var items = qstring.slice(1).split('&');
for (var i = 0; i < items.length; i++) {
var parmset = items[i].split('=');
if(parmset[0].startsWith(matchVal)
vars[parmset[0]] = parmset[1];
}
}
return vars;
}

javascript modify url parameter array

I have a url with an array in it as parameter. For example:
test.dev/orders?filter[]=temp&filter[]=placed
I want to create a js function that can toggle the contents of the array and redirects after the modification.
For example, if i call a function toggleFilter('temp') i want the js to redirect to test.dev/orders?filter[]=placed.
But if i call toggleFilter('processed') i want to have the js redirect to test.dev/orders?filter[]=temp&filter[]=placed&filter[]=processed.
How can i make such function? Thanks in advance!
The function needs to get the current query string, break it down, and then based on the parameters, re-assemble it.
document.location.search - gives you the query string easily enough.
String.split - lets you break it down into its parts.
arguments - lets use this instead of defined parameters so you can pass as many (or as few) filters as you like.
From there, its just interpreting the parameters to assemble a new query string...
function toggleFilter() {
var queryString = document.location.search;
queryString = queryString.substring(1); // Get rid of the initial '?'
// Break it into individual parts and remove the 'filter[]=' leaving just the values
var queryStringSplit = queryString.split('&');
var values = [];
for (var qss = 0; qss < queryStringSplit.length; qss++) {
var value = queryStringSplit[qss];
value = value.split('=')[1];
// This will remove any "blank" values (like 'filter[]=&...")
if (value)
values.push(value);
}
// Add / remove values in arguments
for (var a = 0; a < arguments.length; a++) {
var arg = arguments[a];
var index = values.indexOf(arg);
if (index == -1)
values.push(arg);
else
values.splice(index, 1);
}
// Re-assemble the new query string
queryString = ''; // Default to blank
if (values.length)
queryString = 'filter[]=' + values.join('&filter[]=');
// Redirect to new location
location.search = queryString;
}
Having said that, I think that if you want to make this any kind of reusable, I would call it something like toggleQueryString and modify the logic to interpret the first argument as the name of the queryString value to toggle (so you could do things other than "filter[]") and I would not have it set the location, but instead return a query string value that you could do whatever you want with. But this function should do the trick.
function toggleFilter(url, key) {
var result;
if(url.indexOf('filter[]=' + key) > -1)
result = url.replace('filter[]=' + key + '&', '').replace('filter[]=' + key, '');
else
result = url + (url.indexOf('?') > -1 ? '&' : '?') + 'filter[]=' + key;
result = result.indexOf('?') == result.length - 1 ?
result.substring(0, result.length - 1) :
result;
return result;
// or if you want to redirect just write window.location.href = result;
}

Pull a Specific File name from URL with JavaScript/Jquery

Im trying to pull a specific file name from a URL, Ive looked at the posts but there isnt anything that answers the question that I need. I need a Javascript or Jquery that can pull just the file name ("Test1") from:
http://sharepoint/sites/Jarrod/DurangoTest/SitePages/Home.aspx?RootFolder=%2Fsites%2FJarrod%2FDurangoTest%2FShared%20Documents%2FTest1&FolderCTID=0x01200094D5A58A4F099E49BE1A8BA2F7DE9E0D&View={653454F3-1CE4-48C1-967C-5BA6023D349E}
You can get url information like that from the window.location object. Try this out
params = window.location.search.split(/&/)
for (var i=0; i < params.length; i++) {
if (params[i].match(/^\??RootFolder=/)){
paths = params[i].split(/\//);
filename = paths[paths.length-1];
break;
}
};
#Jonathan is on the right track. It looks like you're looking to parse a value from the querystring rather than find the name of the requested file. You'll first need to get the value from the querystring. You can use window.location.search to get the full querystring from the URL. Then parse the querystring to find the value you want. Here's a little JS function that does that:
// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
if (query.indexOf("?") == 0) { query = query.substr(1); }
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return "";
}
Then you're ready to parse the value using Jonathan's suggestion to get the name of the file. You might have to do some unescaping (using the JS method unescape) to convert the value from the querystring into the "real" value that can be parsed more easily.

Extracting parameters from JavaScript include tag using a Regex

I am currently trying to parse parameters from a path to a JavaScript file (inside a script tag). At the moment I know which parameters I expect to be there but instead of looking for the expected params I would rather like to just extract all params given.
Example of the script tag which includes a JavaScript file:
<script type="text/javascript" src="https://url/widget.js?param1=A&param2=bb></script>
At the moment I'm just doing this (seperately for each parameter):
jQuery('script').each(function() {
var script = this;
if (!script.src) {
return;
}
var matchKey = script.match(/https\:\/\/url\/widget\.js\?param1=([A-Z]+)/);
if (matchKey) {
oSettings.param1 = matchKey[1];
}
}
So what I need is a regex that extracts both the name of the parameter and the value from the included sript.
Thanks for the assistance!
This tested function works:
function parse_query_vars(text)
{ // Extract name=value pairs from URL query string.
// Empty object to store name, value pairs.
var qvars = {},
// Capture non-empty query string in $1.
re_q = /\?([^#]+)/, // From '?' up to '#' or EOS.
// Capture variable name in $1 and value in $2.
re_nv = /([^=]+)=([^&]*)(?:&(amp;)?|$)/gi,
// Match array for query string and va=val pairs.
m = text.match(re_q),
// Query string plucked from URL
q = '';
// If there is a query string, copy to q var.
if (m) q = m[1];
while (m = re_nv.exec(q)) {
qvars[m[1]] = m[2];
}
return qvars; // Return results in object
}
It first extracts any query string from the URL, then iteratively parses out name=value pairs and returns the results in an object. It handles name value pairs separated by either & or & and works if the URL has a #fragment following the query.
Use something like this, or this, or this.
They're not all regex solutions, but then you don't necessarily need a regex. That was a detail that could probably have been left out of the question.
Hope that helps.
(This isn't actually tested)
var scripts = document.getElementsByTagName("script"), i = scripts.length;
var reMatch = /https\:\/\/url\/widget\.js/, path;
// find the correct script
do {
path = scripts[i--].src;
}
while (!reMatch.test(path));
var map = {}, pairs = path.substring(path.indexOf("?") + 1).split("&"), atoms;
i = pairs.length;
// extract the name-value pairs
while (i--) {
atoms = pairs[i].split("=");
map[decodeURIComponent(atoms[0])] = decodeURIComponent(atoms[1]);
}

Can a javascript attribute value be determined by a manual url parameter?

I am trying to display data from an external .jsp file, which is set up something like this:
<tag>
<innertag1 id="1">
<innertag1 id="2">
</tag>
<tag>
<innertag2 id="3">
<innertag2 id="4">
</tag>
To display only information from only one particular "innertag" tag, I'm currently using:
NodeList labs = XMLInfo.getElementsByTagName("innertag1");
I'd like to be able to isolate any particular tag with ease. Theoretically, I could create many individual pages and simply change the values to "innertag2," "innertag3," etc., but this is obviously a bit impractical.
Is there a way to determine the value via a URL parameter? For instance, if I wanted to only display data from "innertag2," is there a way that the url http://www.server.com/data.jsp?id=innertag2 would adjust the tagname properly?
Thank you, any help would be much appreciated.
You can parse document.location.href and extract parameters from there. This is from an old HTML file where I used this technique (not sure if it's compatible on all browsers, however).
var args = {};
function parseArgs()
{
var aa = document.location.href;
if (aa.indexOf("?") != -1)
{
aa = aa.split("?")[1].split("&");
for (var i=0; i<aa.length; i++)
{
var s = aa[i];
var j = s.indexOf("=");
if (j != -1)
{
var name = s.substr(0, j);
var value = s.substr(j + 1);
args[name] = value;
}
}
}
}
Not sure if this is what you're looking for, but you can access parameters from the url using location.search.
6502's answer is almost good enough, it's not url decoding parameters. The function below is a bit more polished (descriptive variable names, no global variables)
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do
var params = getUrlParams();
XMLInfo.getElementsByTagName(params['id']); // or params.id

Categories

Resources