Pull a Specific File name from URL with JavaScript/Jquery - javascript

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.

Related

Parse JSON from url to use in html

i have a json file in an url that appears like this
[{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false},
{"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]7
I want to parse it, either through javascript and use it to display the tier, rank and leaguepoints in html.
I'm new at this, and I cant figure out how to parse the json into usable variables to display in the html file. please help if u can.
You can use jquery to get the json from url
$.getJSON('http://myurl', function(data) {
for(var i = 0, len = data.length; i < len; i++) {
var obj = data[i];
//obj will be your item with obj.tier, obj.leagueName etc.
}
});
Refer to the question How to get JSON from URL in Javascript for accessing the data from the URL. Then you can iterate through the data with a loop:
var data = [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false}, {"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]
for (var i = 0; i < data.length; i++) {
// Within the loop you can access each field of each object
// as shown below
// data[i].tier
// data[i].leagueName
// data[i].queueType
// data[i].playerOrTeamId
// data[i].leaguePoints
// data[i].wins
// data[i].losses
// data[i].rank
// data[i].veteran
// data[i].freshBlood
// data[i].hotStreak
// data[i].inactive
}
You can use methods like document.createElement("TAG_NAME") and document.appendChild(childElement) to insert the data into an HTML document.

Modifying HTTP GET Request via Select Menu Change - Update Parameter

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&param2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing&param2=hello&skip=0
</script>

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'

How to parse URL safe query parameters into readable strings

I found one library, jQuery URL Parser, which seems to be full-featured as far as parsing out the various segments of a URL. I'm trying to go one step further though, and parse the values of the query parameters.
For example, given the URL "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=rm+-rf+%2F" I'd like to get "rm -rf /" for the q parameter. Any suggestions would be greatly appreciated.
As a side note, I'm not operating on the URL of the current page so any location magic doesn't apply.
It looks as though the library you referenced can indeed retrieve query string values as given under the section called Query string parameters:
The .param() method is used to return
the values of querystring parameters.
Pass in a string to access that
parameter's value:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky');
// returns 'blue' If no argument is
passed in it will return an object
literal containing a key:value map of
all the querystring parameters.
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
// returns { 'sky':'blue',
'grass':'green' } Note that the
.param() method will work on both
ampersand-split and semicolon-split
querystrings.
you can use your own small lightweight code to do just that :
function getParam(url, param) {
if (!url.indexOf('?')) {
return 'undefined';
}
url = url.split('?')[1];
var arr = url.split('&');
for (var i = 0; i < arr.length; i++) {
var key = arr[i].split('=')[0], val = arr[i].split('=')[1];
if (key === param) {
return val;
}
}
return 'undefined';
}

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