Get ID from url string - javascript

What is the safest way to get an ID from an URL, which looks like this:
http://www.website.abc.net/fixed/27386323
So I would try to split the string and take the last part:
var parts = url.split("/");
var id = parts[parts.length - 1];
It would also work, if the user types:
www.website.abc.net/fixed/27386323
But it wouldn't work, if the URL would be (last slash)
http://www.website.abc.net/fixed/27386323/
So would a regex be better? Or should I use JQuery?

You can also use a regex for .match:
([^\/]+)\/?$
and grab captured group #1. /?$ makes trailing slash optional in this regex.
RegEx Demo

You may remove any trailing slash at the end of the url and then use the same approach which you are currently doing. This way it would work in both scenarios ( with or without slash ).
var url = 'http://www.website.abc.net/fixed/27386323/';
var url2 = url.replace(/\/$/, ""); // remove any trailing slash at the end
alert(url2.split('/')[url2.split("/").length -1]); // gives the desired id
Example : https://jsfiddle.net/879moj9m/1/

You can simply trim any trailing slash like this:
if(url.substr(-1) === "/") {
url = url.substr(0, str.length - 1);
}
and then check for the id.
var parts = url.split("/");
var id = parts[parts.length - 1];

Related

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)

String replace last character occurrence slash

My url looks like this: ://example/example/.com. I want to remove the last slash of the string. My attempt so far (but doesn't work):
.replace(/\/$/g, '');
Can someone help me along?
You have to escape the slash character in a regular expression literal. Capture the characters after the last slash until the end of the string and use in the replacement:
s = s.replace(/\/([^\/]*)$/, '$1');
(You don't need the g flag for this one, as you know that there is never more than one match.)
Demo: http://jsfiddle.net/Guffa/jkn52/
Alternatively, use a poositive look-ahead to match a slash that doesn't have another slash until the end of the string:
s = s.replace(/\/(?=[^\/]*$)/, '');
Demo: http://jsfiddle.net/Guffa/jkn52/2/
var str = "/1/2/3/4/5"
var index = str.lastIndexOf("/");
var newStr = str.substr(0, index ) + str.substr(index + 1);
console.log(newStr);
demo: http://jsfiddle.net/Jn9bm/
It's a little verbose, but it works:
var url = "//example/example/.com";
var slash_position = url.lastIndexOf('/');
url = url.substr(0, slash_position) + url.substr(slash_position+1);
Try This:
var s= someString.replace(/\//g, "");

converting URL string into slug

I have a string that looks like this "/testpress/about/" and I need to convert it to "about".
I can easily remove testpress by doing the following:
var slug=relativeUrl.replace("testpress", "");
I have not had luck with removing the slashes:
noslash = slug.replace(/\\/g, '');
How can I go about this so I am left with the desired slug?
It is because you are using the wrong slashes
noslash = slug.replace(/\//g, '');
Look here:
> "/testpress/about/".replace(/\//g, '')
'testpressabout'
I like the RegEx method. That way you can see all the path components.
var path = "/testpress/about/";
var pathComponents = path.match(/([^\/]+)/g);
// to get current page... (last element)
var currentPageSlug = pathComponents[pathComponents.length - 1];
This will work regardless of the trailing slash. The good thing is that no matter how deep the URL structure is, you can always get the path components by referencing them as pathComponents[0], pathComponents[1], pathComponents[2], etc ...
With the RegEx method you also do not need to define 'testpress' in the replace/match/split function. That way it makes your code more reusable.
Why don't you use
"testpress/about/".split('\/')
which will yield
["testpress", "about", ""]
and there you have it: second element of the array.
You could also use a regular expression to match everything after the slash but before the end of the string, like so:
var text = "testpress/about";
var slug = text.match(/([^\/]+)\/?$/)[1];
//slug -> "about"
I like #Michael Coxon's answer but the accepted solution doesn't take into account query parameters or things like '.html'. You could try the following:
getSlugFromUrl = function(url) {
var urlComponents = url.match(/([^\/]+)/g),
uri = urlComponents[urlComponents.length - 1];
uri = uri.split(/[\.\?\&]/g);
if (uri.length) {
slug = uri[0];
}
return slug;
};
This should return only the slug and not anything afterwards.
JSBin here: http://jsbin.com/sonowolise/edit?html,js,console

Regex to get string in URL before optional character

I have a URL which may be formatted like this: http://domain.com/space/all/all/FarmAnimals
or like this: http://domain.com/space/all/all/FarmAnimals?param=2
What regular expression can I use to return the expression FarmAnimals in both instances?
I am trying this:
var myRegexp = /\.com\/space\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*\/(.*)/;
var match = myRegexp.exec(topURL);
var full = match[1];
but this only works in the first instance, can someone please provide an example of how to set up this regex with an optional question mark closure?
Thank you very much!
/[^/?]+(?=\?|$)/
Any non-/ followed by either ? or and end-of-line.
I wouldn't write my own regex here and let the Path class handle it (if those are your two string formats).
string url = "http://domain.com/space/all/all/FarmAnimals";
//ensure the last character is not a '/' otherwise `GetFileName` will be empty
if (url.Last() == '/') url = url.Remove(url.Length - 1);
//get the filename (anything from FarmAnimals onwards)
string parsed = Path.GetFileName(url);
//if there's a '?' then only get the string up to the '?' character
if (parsed.IndexOf('?') != -1)
parsed = parsed.Split('?')[0];
You could use something like this:
var splitBySlash = topURL.split('/')
var splitByQ = splitBySlash[splitBySlash.length - 1].split('?')
alert(splitByQ[0])
Explanation:
splitBySlash will be ['http:','','domain.com', ... ,'all','FarmAnimals?param=2'].
Then splitByQ will grab the last item in that array and split it by ?, which becomes ['FarmAnimas','param=2'].
Then just grab the first element in that.
This
.*\/(.*?)(\?.*)?$
Should capture the part of the string you are looking for as the group 1 (and the query after ? in group 2, if needed).
var url = 'http://domain.com/space/all/all/FarmAnimals?param=2';
//var url = 'http://domain.com/space/all/all/FarmAnimals';
var index_a = url.lastIndexOf('/');
var index_b = url.lastIndexOf('?');
console.log(url.substring(index_a + 1, (index_b != -1 ? index_b : url.length)));

How can I change the last component of a url path?

"http://something.com:6688/remote/17/26/172"
if I have the value 172 and I need to change the url to 175
"http://something.com:6688/remote/17/26/175"
how can i do that in JavaScript?
var url = "http://something.com:6688/remote/17/26/172"
url = url.replace(/\/[^\/]*$/, '/175')
Translation: Find a slash \/ which is followed by any number * of non slash characters [^\/] which is followed by end of string $.
Split the String by /, remove the last part, rejoin by /, and add the new path
newurl = url.split('/').slice(0,-1).join('/')+'/175'
new URL("175", "http://something.com:6688/remote/17/26/172").href
This also works with paths, e.g.
new URL("../27", "http://something.com:6688/remote/17/26/172").href → "http://something.com:6688/remote/17/27"
new URL("175/1234", "http://something.com:6688/remote/17/26/172").href → "http://something.com:6688/remote/17/26/175/1234"
new URL("/local/", "http://something.com:6688/remote/17/26/172").href →
"http://something.com:6688/local/"
See https://developer.mozilla.org/en-US/docs/Web/API/URL/URL for details.
Split the String by / then change the last part and rejoin by /:
var newnumber = 175;
var url = "http://something.com:6688/remote/17/26/172";
var segements = url.split("/");
segements[segements.length - 1] = "" + newnumber;
var newurl = segements.join("/");
alert(newurl);
Try it!
Depends on what you want to do.
Actually change browser URL:
If you actually want to push the browser to another URL you'll have to use window.location = 'http://example.com/175'.
Change browser URL hash
If you just want to change the hash you can simply use window.location.hash.
Re-use the URL on links or similar
If you want to reference a URL in links or similar, look into George's answer.
//Alternative way.
var str = window.location.href;
var lastIndex = str.lastIndexOf("/");
var path = str.substring(0, lastIndex);
var new_path = path + "/new_path";
window.location.assign(new_path);

Categories