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);
Related
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);
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"]
So let's say there's a URL http://example.com/index.html/hello/hi where "hello" and "hi" are parameters.
How would you use javascript and forms method POST to extract the parameters?
Your subject is a little bit vague. However, I thought I'd made an example of possibilities.
http://jsfiddle.net/tive/LjbPq/
The idea is to split the URL for each character /, in whatever way you received it.
var parts = document.URL.split("/");
Since split() returns an array (zero based), you need to distract 1 from the total length to get the last index.
var lastPart = parts[parts.length - 1];
Run this in a for loop, and you should get the idea as occurring in the example.
documentation on document.URL to retreive the complete URL
documentation on window.location to use properties of a url (protocol, href, pathname, ...)
this could work...
var secondvar = window.location.href.split('/')[window.location.href.split('/').length];
var firstvar = window.location.href.split('/')[window.location.href.split('/').length-1];
I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.
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