How to get last two URL segments? - javascript

What is the best way to get the last two URL segments?
To get the last segment is pretty easy url.substr(url.lastIndexOf('/') + 1)
Here is an example, say I have this url http://mywebsite/segment1/segment2
So I want to get segment1/segment2
Is there a better way than just using url.split("/");?

Splitting, slicing and joining is probably the easiest:
const url = 'http://mywebsite/segment1/segment2';
const lastTwo = url.split('/').slice(-2).join('/');
console.log(lastTwo);

You can use this as a reference :
Take out the pathname, and then do the string.split, it would also protect you from the content after the ? sign (url parameters).

Related

Get the middle ID after the "com/ in the url string below in JavaScript

I would like to extract the middle ID from below string
const url = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";
And I want to grab the middle ID = "11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87" from the string
Should I just use substring and index of or are there other ways of doing that. Please help
Using the built-in URL api is probably the canonical way and the safest way to do it:
const urlString = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";
const url = new URL(urlString);
console.log(url.pathname.split("/")[1]);
URLs can get pretty crazy, so we should just rely on the built-in way to parse it for us :)

Problem Splitting Code at '%2F', not at '/'

So, I'm working on a bookmarklet that takes the website url, which contains the actual text '%2F' in it, and split it there. However, because %2F represents a forward slash, it keeps splitting where there are forward slashes and not at %2F. How can I fix this?
Current Code:
javascript:(
function(){
var str = window.location.href;
var res = str.split("%2F");
alert(res); //Just here to test the output
}
)
();
Example Input:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Example Output:
http:,,blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Wanted Output:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com ,4uHAdNPg.jpg
It looks like you want you focus your splitting more to a specific portion of the location rather that the whole URL. In your case, it looks like you really want to split the value of the url variable which is found in window.location.search. You can probably accomplish close what you want if you just use that instead of window.location.href.
A better approach might be to target the actual value of the url variable.If you don't need to support IE, an easy way to get that data is to use UrlSearchParams:
const params = new URLSearchParams(window.location.search);
const url = params.get("url");
const res = url.split('%2F');
If you do need more cross browser reach, you can also do this with a simple regular expression:
const url = window.location.search.match(/url=[^&]+/)
const res = url.split('%2F');
The split works as expected:
const str = 'http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg';
console.log(str.split('%2F'));
But window.location.href doesn't always return exactly the same string that is being displayed in the address bar, or encode stuff without you knowing about it. It is quite browser-dependent. For example, on chrome, you might observe this:
location.href = 'http://example.com/ xxx';
console.log(location.href); // http://example.com/%20xxx
In any case, it just looks like you're trying to manipulate your URL by hand. Don't do that. By using new URL(...), location.searchParams, decodeURIComponent, and other native APIs to easily manipulate URLs, you'll probably achieve what you're looking for in an easier and safer way ;)

How to extract specific parameter from different URLs

I've looked on similiar topics but no one seems to answer my question.
I've URL that looks like this:
https://dummy.com/job/test
I need to extract test so I am using:
function getIdentificator(){
let URL = window.location.pathname;
let Id = URL.slice(URL.lastIndexOf('/') + 1);
return Id;
}
It gives me what I want but sometimes the URL is different. For example:
https://dummy.com/job/testwz/something
I only need testwz.
Or:
https://dummy.com/job/test-ab?somethingmore2132
I only need test-ab.
Or:
https://dummy.com/job/test
I only need test.
Or:
https://dummy.com/job/5423
I need 5423 from this.
Value I'm interested in always appear after job/ but in different variations as said before. Key value may be followed by: nothing, / or ?.
Is there any way to extract this value in all examples with JavaScript? If not I can use jQuery as well.
Assuming your path will always begin with /job no matter the domain:
return window.location.pathname.split('/')[2]
I'm going to give you this example:
this is the question's url:
https://stackoverflow.com/questions/54556911/how-to-extract-specific-parameter-from-different-urls
if you do window.location.pathname you will get :
"/questions/54556911/how-to-extract-specific-parameter-from-different-urls"
now, if you do...
window.location.pathname.split('/').pop()
you will get:
how-to-extract-specific-parameter-from-different-urls
And I think this is the answer you are looking for.

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.

Using forms and POST method to get URL parameters through Javascript

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];

Categories

Resources