I have a search results page in a PHP site that returns a list of results using pagination. The URL looks like this:
findProducts.php?action=searchAssets&orderNumber=xxxx&productName=zzz&skip=20
I have a select menu that allows the user to modify/filter the search results which triggers a script like this:
$(document).ready(function() {
$('#productType').change(function() {
window.location.href = window.location.href + '&productType=' + $(this).val();
});
});
This is working well except for one thing - I need to reset the 'skip' parameter to 0 for the new filter search as the pagination values from the previous search won't be valid or applicable. Is there a way I can change:
skip=20
to:
skip=0
as part of this script?
You could do a RegExp replace on the URL:
window.location.href = window.location.href.replace(/((?:\?|&)skip)=\d+/, '$1=0') + '...';
(untested)
Note that you should do the same with the productType because otherwise you'll add it again and again.
Better solution would possibly be to have a base URL and then add all necessary parameters instead of doing search and replace...
You can get the query from the URL by splitting the URL using ?
This will give you the base url in the first index and the query in the second.
You can then get the query parameters by splitting the query using &.
You can loop through all of the parameters checking if it is the skip parameter. If the parameter is the skip parameter push your new value to an output array. Otherwise push the unchanged parameter to an output array.
You can then use join to join all of your output elements using & to reconstruct the query and return your original base url with your new query string.
<script>
function fixQuery(qstr) {
var parts = qstr.split('?');
var query = parts[1];
var a= query.split("&");
var out=[];
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
if(decodeURIComponent(b[0])=="skip")
{
out.push("skip=0")
}
else {
out.push(a[i]);
}
}
return parts[0] + '?' + out.join("&");
}
var result= fixQuery("http://example.com/findProducts.php?param1=test+thing¶m2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing¶m2=hello&skip=0
</script>
i have an array of urls. I insert into it values like this :
var replacementArray=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
This is an example of one such URL array:
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
I have to compare the shorturl of this array with a string. If the strings match then i retrieve the url. Here is my first attempt at doing this :
var chaine="xfm1";//this is an example
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j][shorturl]==chaine){
var url= replacementArray[url];
}
This seems to not be working. Why is that?
Associative arrays with arbitrary keys don't exist in javascript
You can have data that works as an associative array, but then you need to use an object to store the keys.
The example data you provided is not valid JS. It is an object of arrays instead of being an array of objects. For your function to work as expected, the data
needs to be in the following format:
[
{
url: 'tuto.com',
shorturl: 'xfm1'
},
{
url: 'youtube.com',
shorturl: 'xfm2'
},
// etc...
]
The [] is for creating an array, which will have numeric indexes only.
The {} creates objects that can store key-value pairs like an associative array in other languages.
So in your function you can loop through the array indexes by incrementing i and access the values associated with your keys using replacementArray[i].shorturl or replacementArray[i]['shorturl'] (notice the string) - the way you do it is up to your preference, they both work the same.
Hope this helps!
var arr=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
insert(arr,"google.com", "xfm.io1");
insert(arr,"gogle.com", "xfm.io2");
insert(arr,"gole.com", "xfm.io3");
function getUrl(yourVariable){ //chaine
for(var j=0;j<arr.length;j++)
if (arr[j].shorturl == chaine){
return arr[j].url;
}
return null;//not found yourVariable
}
var chaine= "xfm.io1"; //your Short URL
console.log(getUrl(chaine)); //testing the function
First of all you given: (which is not an acceptable data structure)
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
which must be like this: (array of objects)
replacementArray:[
{url:"tuto.com", shorturl:"xfm1"},
{url:"youtube.com", shorturl:"xfm2"},
{url:"google.com",shorturl:"xfm3"}]
Then to get shortUrl code will be like
function getUrl(yourVariable){ //chaine
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j].shorturl == chaine){
return replacementArray[j].url;
}
return null;//not found yourVariable
}
Read over these corrections/suggestions:
As others have mentioned, you should create an array of objects, instead of an object with arrays
Reference the property 'shorturl' either using array syntax (i.e. replacementArray[j]['shorturl']) or dot notation (i.e. replacementArray[j].shorturl). If you use array syntax then the property needs to be in a string literal (unless you create a variable to represent the field - e.g. var shorturl = 'shorturl';).
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var url; //declare url here so it won't be undefined if no url is found in the array
for (var j = 0; j < replacementArray.length; j++) {
if (replacementArray[j]['shorturl'] == chaine) {
//need to reference replacementArray[j] instead of replacementArray['url']
url = replacementArray[j]['url'];
}
}
console.log('url: ',url);
Consider using Array.prototype.find() or a similar functional-style method (e.g. filter() if you wanted to find multiple values) to determine the site with the matching shorturl value. That way you don't have to worry about creating and incrementing the iterator variable (i.e. j) and using it to reference elements in the array. For more information, try these exercises about functional programming in JS.
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var foundSite = replacementArray.find(function(site) {
return (site.shorturl == chaine);
});
if (foundSite) { //if we did find a matching site
var url = foundSite.url;
console.log('url: ',url);
}
Try this in your 'for' loop:
if(replacementArray[j].shorturl == chaine){
// Do stuff here...
}
With [shorturl], you are accessing a property name based on the value of shorturl, which is not defined.
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'
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.
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¶m2=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]);
}