Grabbing a url variable from a string? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript REGEX: How to get youtube video id from URL?
In javascript I need to grab a url variable that can be the first variable but doesn't have to. The url is a string of a url from Youtube. At first I was using regex to replace everything from & on, but then I found out that the video variable isn't always first. I am not good with regex and just have gone with tutorials I can find and double check to make sure it works right. So I need to be able to grab the v=videoletters part. If I can grab that, I think I can figure from then on to make the normal youtube url which is what I need.

Here's a function that does exactly what you asked for:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Found via a Google search on this page: http://www.netlobo.com/url_query_string_javascript.html
So, you would just do:
var videoletters = gup("v");
There are many, many other ways to do this also that you can see via your own search. Here are a few of the others:
How to retrieve query string parameter and values using javascript (Jquery)?
http://www.idealog.us/2006/06/javascript_to_p.html
http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
http://geekswithblogs.net/PhubarBaz/archive/2011/11/21/getting-query-parameters-in-javascript.aspx

Related

How to get access token from the url [duplicate]

This question already has answers here:
Parsing URL hash/fragment identifier with JavaScript
(10 answers)
Closed 7 years ago.
I'm getting this URL after I'm authenticated to Google
http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600
How to get access_token value from this url?
I tried solutions in following urls, none of them are working
How can I get query string values in JavaScript?
How to get the value from the GET parameters?
Using the GET parameter of a URL in JavaScript
Using modern ways, there are better, more reliable ways to get access token field:
var urlString = 'http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600';
var url = new URL(urlString);
// OR: If you want to use the current page's URL
var url = window.location;
var access_token = new URLSearchParams(url.search).get('access_token');
You can also see how this approach makes it easy to get the other parameters in addition. This URLSearchParams approach is supported by all browsers except old instances of IE.
If the above doesn't work (didn't for me) just add 'hash' to window.location, this is also single line code
var access_token = new URLSearchParams(window.location.hash).get('access_token');
Old Answer:
I like RegEx so here's a RegEx answer:
var url = 'http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600',
access_token = url.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1];
access_token is:
ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw
(Directly from the console)
Fiddle
Make use of the URL class in JS:
var token = new URL("http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600").hash.split('&').filter(function(el) { if(el.match('access_token') !== null) return true; })[0].split('=')[1];
alert(token);

How to get base url from FTP address?

For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.

Extract values of substring of parameters from string [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have a string of the form
p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31 and so on
I want to get an array of all values for p2 in javascript, e.g. in this example it would be ["v21", "v22", "v23"].
How do I do it? Do I need to use regex?
You might want to have a look at a JavaScript function I wrote to mimic the $_GET function in PHP:
http://www.martinandersson.com/matooltip/js/ma_GET.js
Google the source code for this line:
returnMe[key] = $.parseJSON( decodeURIComponent(tmpArray[1]) );
The problem with my current implementation is that any old key already stored, will have his value overwritten. What you need to do is to check if the key is already present, if so, read the old value and store him back in an array before you push the new value onto the same array.
The particular line i quoted uses JQuery to make the value into a JavaScript object. If you don't want to use JQuery for this feature then you could use JSON.parse or some other third party library.
Hope it helps, write me a comment if you don't succeed and I'll get back to you.
Try this:
var string = 'p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31';
var rawParams = string.split('&');
var params = [];
var param = '';
for (var i in rawParams) {
param = rawParams[i].split('=');
if ('p2' == param[0]) {
params.push(param[1]);
}
}
I don't recommend RegExp here, since the problem is pretty easy to be resolved with one simple for loop.
EDIT:
For sake of any haters - here's the working example: http://jsfiddle.net/j7sY6/1/
For a regex solution:
var matchs = [];
var re = /p2=([^&]+)/g;
while (match = re.exec('p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31')) {
matchs.push(match[1]);
}
Output:
matches = ["v21", "v22", "v23"]

html link variable

Is it possible to pass two variables through to another html page through a link?
For example... I have a directory page where when a user clicks a store link, it links to another html page with the map centered on the specific store. The function that centers the map on the store takes two variables, storeID, storeName. There are hundreds of stores and currently I would have to manually create each store page separately by hardcoding those two variables so that each page loads slightly differently. Is there a way to pass these two variables with a link, to avoid many different html pages?
Perhaps something along the lines of <a href "thisPage.html", var1, var2>?
ex. code
thispage.html
var1;
var2;
function myFunc(var1, var2) {
~~~
}
Not like that, but you can use URL parameters.
thisPage.html?var1=foo&var2=bar
Then you can read them on the second page. I like to use this function for that:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
From http://www.netlobo.com/url_query_string_javascript.html
So on your second page, you can just do gup("var1") and you will get foo.
Use a query string.
In a URL a ? indicates the start of the query. It consists of a series of key=value pairs separated by & characters.
The encodeURIComponent function will escape text for inserting as a key or a value.
You can then assign it to the href attribute of the link element or set location.href to it.

Javascript to grab last part of the document.URL? [duplicate]

This question already has answers here:
Last segment of URL with JavaScript
(30 answers)
Closed 12 months ago.
I am trying to grab the last part of the current url:
URL: http://example.com/test/action
I am trying to grab "action".
The URL is always consistent in that structure. But it may have some extra params at the end.
This is in a rails app using the prototype framework. In rails it would be params[:id].
You could simply use .split() on window.location.href, and grab the last entry.
Example:
var lastPart = window.location.href.split("/").pop();
The other answers are fine, however if your url looks like:
http://example.com/test/action?foo=bar
they will fail to give you just "action". To do this you'd use pathname, which contains only the path information exclusive of query string parameters (ie /test/action in this case):
location.pathname.split('/').pop();
use document.location.href.substring( document.location.href.lastIndexOf( '/' ) );
with jquery :
var idFromUrl = window.location.href.split("/").pop();
$('#various3').attr('href', $('#various3').attr('href').replace('placed_id', idFromUrl));
Below is my working javascript solution.Hope it helps some one and hence posting.This solution is to retrieve last part of url leaving the generally not needed query string part.It helps to identify from which page the visit happened and write logic based on that.
var url = document.referrer;
var start = url.lastIndexOf("/") + 1;
var len = url.indexOf("?");
if (len > 0)
url = url.substring(start, len);
else
url = url.substring(start);

Categories

Resources