Get the second last parameter in a url using javascript - javascript

I have a url like this
http://example.com/param1/param2/param3
Please help me get the second last parameter using javascript. I searched and could only find regex method to find the last parameter. I am new to this. Any help would be greatly appreciated.
Thanks.

var url = 'http://example.com/param1/param2/param3';
var result= url.split('/');
var Param = result[result.length-2];
Demo Fiddle:http://jsfiddle.net/HApnB/
Split() - Splits the string into an array of strings based on the separator you mentioned
In the above , result will be an array that contains
result = [http:,,example.com,param1,param2,param3];

Basic string operations:
> 'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
"param2"

You can do this by:
document.URL.split("/");

var url='http://example.com/param1/param2/param3';
var arr = url.split('/');
alert(arr[arr.length-2]);
arr[arr.length-2] will contain value 'param2'. Second last value

var url = "http://example.com/param1/param2/param3";
var params = url.replace(/^http:\/\/,'').split('/'); // beware of the doubleslash
var secondlast = params[params.length-2]; // check for length!!

var url = "http://example.com/param1/param2/param3";
var split = url.split("/");
alert(split[split.length - 2]);
Demo: http://jsfiddle.net/gE7TW/
The -2 is to make sure you always get the second last

My favorite answer is the following from #Blender
'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
However all answers suffer from the edge case syndrome. Below are the results of applying the above to a number of variants of your input string:
"http://example.com/param1/param2/param3" ==> "param2"
"http://example.com/param1/param2" ==> "param1"
"http://example.com/param1/" ==> "param1"
"http://example.com/param1" ==> "example.com"
"http://example.com" ==> ""
"http://" ==> ""
"http" ==> "http"
Note in particular the cases of the trailing /, the case with only // and the case with no /
Whether these edge cases are acceptable is something you will need to determine within the larger context of your code.
Do not validate this answer, choose from amongst the others.

Just another alternate solution:
var a = document.createElement('a');
a.href = 'http://example.com/param1/param2/param3'
var path = a.pathname;
// get array of params in path
var params = path.replace(/^\/+|\/+$/g, '').split('/');
// gets second from last parameter; returns undefined if not array;
var pop = params.slice(-2)[0];

Related

How to get string in path from split?

it didn't work on stackoverflow snippet but if you try on your local you will see it's going to work.
js give me a this result
cdn=//cdn.files.com/web
but I dont want to this line
cdn=
js must give me after from cdn= I mean result must be like this
//cdn.files.com/web
my all js is below so how to do that ?
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\=]+\??/,'');
alert(decodeURIComponent(queryString));
<script src="//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb"></script>
<p></p>
var s = "cdn=//cdn.files.com/web";
s2 = s.substring(s.indexOf("cdn=")+4,s.length);
alert(s2);
this will substring from the index next to equals character to the end of yours string :)
fixed and tested
Split the string by '?cdn=' and get the part after that(second element in the result array, at index 1).
var queryString = myScript.src.split('?cdn=')[1];
FYI : If there is only one URL param then you can simply use = or cdn= for splitting.
You can use split:
yourvariable.split('=');
So whatever your arguments into GET, the odd param will get your desired result.
PS: Prefer just the = char, because you can work with whatever param you want into link gived by src.
why can't you use ^.+?cdn= in your regex?
this will give you strings after the cdn=
var myScript = '//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb';
var queryString = myScript.replace(/^.+?cdn=/, '');
console.log(decodeURIComponent(queryString));
Solution with regex
var src = 'cdn=//cdn.files.com/web';
var url = src.replace(/^([^\=]+=)(.*)$/, '$2');
console.log(decodeURIComponent(url));
DEMO with explanation

Get content between second last and last slash

I have a url like the following
http://localhost:8000/test/
What is the tidiest way of getting test from this using plain javascript/jQuery?
You can do it easily like following using split() method.
var str = 'http://localhost:8000/test/';
var arr = str.split('/');
console.log(arr[arr.length-2])
The section of the URL you are referring to is called the path, in Javascript this can be accessed by reading the contents of the location.pathname property.
You can then use a regular expression to access only the final directory name (between the last two slashes).
Don't you guys like regex? I think it is simpler.
s = 'http://localhost:8000/test/';
var content = s.match(/\/([^/]+)\/[^/]*$/)[1];
JS split() function does magic with location.pathname .
var str = location.pathname.split('/');
var requiredString = str[str.length -2];
requiredString will contain required string, you may console log it by console.log(requiredString) or use it anywhere else in the program.
let arr = link.split('/');
let fileName = arr[arr.length - 2] + "/" + arr[arr.length - 1];
It will return all data after second last /.
You can use :
window.location.pathname
returns the path and filename of the current page.
with the split() function
To learn more about window.location in w3 School :
https://www.w3schools.com/js/js_window_location.asp
//window.location.pathname return /test
var path=window.location.pathname.split("/");
var page=path[0]; //return test`

How to split a word for getting a specific value in Javascript or Jquery? [duplicate]

How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
If the url is
http://mywebsite/folder/file
how do I only get it to display the "file" part of the url in the alert box?
You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split() does.
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
window.location.pathname.split("/").pop()
The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.
Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:
Input:
const href = 'https://stackoverflow.com/boo?q=foo&s=bar'
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
Output: 'boo'
This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
Javascript has the function split associated to string object that can help you:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
Shortest way how to get URL Last Segment with split(), filter() and pop()
function getLastUrlSegment(url) {
return new URL(url).pathname.split('/').filter(Boolean).pop();
}
console.log(getLastUrlSegment(window.location.href));
console.log(getLastUrlSegment('https://x.com/boo'));
console.log(getLastUrlSegment('https://x.com/boo/'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo&s=bar=aaa'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));
Works for me.
Or you could use a regular expression:
alert(href.replace(/.*\//, ''));
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
I know, it is too late, but for others:
I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like
http://test.com/#/about/us/
or
http://test.com/#sky=blue&grass=green
And with PURL you can easy decide (segment/fsegment) which segment you want to get.
For "classic" last segment you could write:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
Get the Last Segment using RegEx
str.replace(/.*\/(\w+)\/?$/, '$1');
$1 means using the capturing group. using in RegEx (\w+) create the first group then the whole string replace with the capture group.
let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).
url.split('/').filter(function (s) { return !!s }).pop()
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.
If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
you can first remove if there is / at the end and then get last part of url
let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href;
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);
targetValue = one
If your url looks like:
http://test.com/one/
or
http://test.com/one
or
http://test.com/one/index.htm
Then loc ends up looking like:
http://test.com/one
Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
// Store original location in loc like: http://test.com/one/ (ending slash)
let loc = "http://test.com/one/index.htm";
console.log("starting loc value = " + loc);
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
let targetValue = loc.substring(loc.lastIndexOf('/') + 1);
console.log("targetValue = " + targetValue);
console.log("loc = " + loc);
Updated raddevus answer :
var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
Prints last path of url as string :
test.com/path-name = path-name
test.com/path-name/ = path-name
I am using regex and split:
var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]
In the end it will ignore # ? & / ending urls, which happens a lot. Example:
https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm
I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:
[^\/]+[\/]?$
I know it is old but if you want to get this from an URL you could simply use:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname gets the pathname from the current URL.
lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL.
substring will cut the string between two indexes.
if the url is http://localhost/madukaonline/shop.php?shop=79
console.log(location.search); will bring ?shop=79
so the simplest way is to use location.search
you can lookup for more info here
and here
You can do this with simple paths (w/0) querystrings etc.
Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
Split the string on path separators.
Filter out empty string path parts (this could happen with trailing slash in path).
Reduce the array of path parts to the last one.
Adding up to the great Sebastian Barth answer.
if href is a variable that you are parsing, new URL will throw a TypeError so to be in the safe side you should try - catch
try{
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
}catch (error){
//Uups, href wasn't a valid URL (empty string or malformed URL)
console.log('TypeError ->',error);
}
I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
Bestway to get URL Last Segment Remove (-) and (/) also
jQuery(document).ready(function(){
var path = window.location.pathname;
var parts = path.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
lastSegment = lastSegment.replace('-',' ').replace('-',' ');
jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
});
A way to avoid query params
const urlString = "https://stackoverflow.com/last-segment?param=123"
const url = new URL(urlString);
url.search = '';
const lastSegment = url.pathname.split('/').pop();
console.log(lastSegment)

Get substring between two last instances of character in url

I have urls which look like this :http://i1.ytimg.com/vi/BR0Y3MZ21bo/0.jpg. Can someone help me extract the "ID" BR0Y3MZ21bo between the last two slashes in the url?
You can use split(), split will give you array of string being separated by / and your desired string is at second last index of array.
Live Demo
arr = url.split('/');
arr[arr.length-2];
Try this:
var url = 'http://i1.ytimg.com/vi/BR0Y3MZ21bo/0.jpg'; // window.location.href;
var page = url.substr(0, url.lastIndexOf('/')); // output -> http://i1.ytimg.com/vi/BR0Y3MZ21bo
var str = page.substr(page.lastIndexOf('/')+1); // output -> BR0Y3MZ21bo
alert(str); // BR0Y3MZ21bo
FIDDLE

JavaScript indexOf() - how to get specific index

Let's say I have a URL:
http://something.com/somethingheretoo
and I want to get what's after the 3rd instance of /?
something like the equivalent of indexOf() which lets me input which instance of the backslash I want.
If you know it starts with http:// or https://, just skip past that part with this one-liner:
var content = aURL.substring(aURL.indexOf('/', 8));
This gives you more flexibility if there are multiple slashes in that segment you want.
let s = 'http://something.com/somethingheretoo';
parts = s.split('/');
parts.splice(0, 2);
return parts.join('/');
Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches.
String.prototype.nthIndexOf = function(s, n) {
var i = -1;
while(n-- > 0 && -1 != (i = this.indexOf(s, i+1)));
return i;
}
var str = "some string to test";
alert(str.nthIndexOf("t", 3)); // 15
alert(str.nthIndexOf("t", 7)); // -1
alert(str.nthIndexOf("z", 4)); // -1
var sub = str.substr(str.nthIndexOf("t",3)); // "test"
Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in.
If you want to stick to indexOf:
var string = "http://something/sth1/sth2/sth3/"
var lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
string = string.substr(lastIndex);
If you want to get the path of that given URL, you can also use a RE:
string = string.match(/\/\/[^\/]+\/(.+)?/)[1];
This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /.
Another approach is to use the Javascript "split" function:
var strWord = "me/you/something";
var splittedWord = strWord.split("/");
splittedWord[0] would return "me"
splittedWord[1] would return "you"
splittedWord[2] would return "something"
It sounds like you want the pathname. If you're in a browser, keep an a element handy...
var _a = document.createElement('a');
...and let it do the parsing for you.
_a.href = "http://something.com/somethingheretoo";
alert( _a.pathname.slice(1) ); // somethingheretoo
DEMO: http://jsfiddle.net/2qT9c/
In your case, you could use the lastIndexOf() method to get the 3rd forward slash.
Here's a very cool way of handling this:
How can I remove all characters up to and including the 3rd slash in a string?
My preference of the proposed solutions is
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Inestead of using indexOf it is possible to do this this way:
const url = 'http://something.com/somethingheretoo';
const content = new URL(url).pathname.slice(1);

Categories