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.
Related
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 ;)
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.
I have already searched from this question in SO. But none of the answers worked for me, so I am posting this once more in the hope to find an answer that works for me.
Is there a way to pass JS/JSON objects through URL? Suppose I have a JS Object like so:
var jObj = {"color":"red","shape":"square"}
Now suppose I want to pass it to a URL like so:
window.open("/process/jObj"); //here I want the var defined above to be passed
I tried various options like JSON.stringfy, encodeURIComponent, escape..but I am not able to pass it around. Any idea how this can be achieved in pure JS?
I would like to pass it so that in the next page (process.php) such that there I can get the values of jObj and use it for further processing. Basically I am looking for an option where I can pass the object to the effect of ?color=red&shape=square without having to squash and reformat the object too much
Here is one thing you can do
var jObj = {"color":"red","shape":"square"}
var urlParam = []
for (var i in jObj){
urlParam.push(encodeURI(i) + "=" + encodeURI(jObj[i]));
}
window.open("/process/?" + urlParam.join("&"));
this should produce your result
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 am in need of two regular expressions.
First of all I want to check if my URL contains the hashtag #videos. Then if it does, I want to get the value of the second #tag. That value could contain all kinds of characters;
http://local/default.php#videos#12345
http://local/default.php#videos#g5458f
http://local/default.php#videos#0-e4a5d
This is what I've got so far:
if (window.location.hash = 'videos') {
var url = window.location.hash,
id = url.match(regex-goes-here); // output e.g string '12345'
}
(Not sure if my extremely simple check (window.location.hash = 'videos') will work on two hashtags..? There is probably a better way of checking the URL, if so, please do tell :-)
You can get an array of tags like this:
var tags = window.location.hash.replace(/^#/, '').split('#');
In case of http://local/default.php#videos#12345, tags[0] will be videos and tags[1] will be 12345. You can use tags.length to determine how many tags there are.