Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.
Here's an example of what I'm talking about (I know this doesn't work):
var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
Is anything like this possible or would I essentially have to create this object myself?
Well, you could use an anchor element to extract the url parts, for example:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
It works on all modern browsers and even on IE 5.5+.
Check an example here.
How about use the standard URL object?
const url = new URL("http://www.example.com/some/path?name=value#anchor");
const { hash } = url;
Then console.log(hash) will output #anchor.
Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility table and do your tests at target browsers.
You can leverage the power of an anchor element
var aLink = document.createElement("a");
aLink.href="http://www.example.com/foo/bar.html?q=123#asdf";
alert(aLink.pathname);
You can parse it in a regex to get the parts as matches... I don't have the full code right now, but this can be used to get the querydata:
var myUrl = window.location.href;
var matches = myUrl.match(/([^\?]+)\?(.+)/);
var queryData = matches[2];
matches[0] is the full string, matches(1) is the first part of the URL (up to the ?)... you could build up a regular expression to parse each part of a string url if you want...
You can also use one of the many libraries already out there for this.
Related
I'm changing current user's path through a function:
function setSomeValue(someValues) {
var query = '';
for (var i = 0; i < someValues.length; i++) {
query += someValues[i] + ',';
}
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("paramName", query);
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
}
As you can see, I'm adding to user's location new words and want new location to be like this:
www.site.com?paramName=value1,value2,
But browser converts my commas into %2C so I get this:
www.site.com?paramName=value1%2Cvalue2%2C
What should be done to make pushing commas to URL possible?
(copy & paste from several comments)
It might be due to URLSearchParams and its toString method implementation - but we can’t know, because you have not shown us what that actually is. If that is not deliberately encoding the comma, and the browser simply does it automatically - then there’s little you can do about that.
If newRelativePathQuery contains the encoded versions already, maybe they could be replaced back to normal commas. But if history.pushState does it, then “other ways” to create the URL itself won’t help you much.
Since a debug output showed that newRelativePathQuery contains the encoded commas already, you can try and replace them back to commas, and see if that “survives” being pushed to the history then.
It's a little hacky, but here's one solution. Let's say we want to use URL's searchParams.set() to set ids=1,2,3,4 in our query string.
If you just do url.searchParams.set("ids", "1,2,3,4"), the URL will have ids=1%2C2%2C3%2C4. To avoid that encoding, first set ids=LIST_OF_IDS_PLACEHOLDER, get the URL as a string, and then replace LIST_OF_IDS_PLACEHOLDER with 1,2,3,4, like this:
const myList = [1,2,3,4],
url = new URL(document.location.href); // or however you get your URL object
url.searchParams.set("ids", "LIST_OF_IDS_PLACEHOLDER");
const newUrlString = url.toString().replace("LIST_OF_IDS_PLACEHOLDER", ids.join(','));
console.log(newUrlString); // this will include: ids=1,2,3,4
I'm trying to make a bookmarklet that will take part of an URL and redirect to the new URL, but I need to change two parts of the URL that are separate.
The base URL could be:
78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png
I need it to end like this:
s3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png
So I need to replace "78.media.tumblr.com" and "1280"
I've tried coming up with something using window.location.assign and location.href.replace but I'm pretty new and couldn't figure it out.
You can do this with regex and window.location.href. This is assuming you are only looking at tumbler though. If you're not, there would be another step in the regex.
// first get the url
var url = window.location.href;
// Use regex to keep only the parts we want and replace the others
var newUrl = url.replace(/.*(\.tumblr.*\_).*(\..*)/, 'http://s3.amazonaws.com/data$1raw$2')
// go to the new page
window.location.href = newUrl;
In general, you can just replace the parts of the string using String.prototype.replace. Depending on how flexible you need the matching to be you can adjust the regexes to be more or less 'matchy'.
const startUrl = '78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png'
const endUrl = 's3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png'
const tumblerRegex = /.*\.tumblr\.com/
const numberRegex = /_\d{4}/
function transform (start) {
return start.replace(tumblerRegex, 's3.amazonaws.com/data.tumblr.com').replace(numberRegex, '_raw')
}
console.log(transform(startUrl) == endUrl)
I am building a javascript bookmarklet which can change some part of url and can open updated URL. Below is the code I have written.
var str = "www.myweb.com/in/products/index.aspx";
var pattern2 = new RegExp('www.myweb.com','i');
var str1 = str.replace(pattern2, 'https://www-stg.myweb.com:60002');
window.location.href = str1;
This is resulting in http//www-stg.myweb.com:60002/in/products/index.aspx which in incorrect. I want to add https:// before www-stg.myweb.com
If I alert it or console.log() it, it will show correct thing. But browser is adding http once submitted.
How to overcome this?
I suggest to use an anchor element for such operations. No need for complicated expressions.
var str = '//www.myweb.com/in/products/index.aspx';
var a = document.createElement('a');
a.href = str;
a.protocol = 'https';
a.host = 'www-stg.myweb.com:60002';
console.log('result', a.href);
Fiddle
Make sure str begins with // or http://, otherwise the current hostname will be used.
I have following url's and all these url are considered root of the website, how can I use javascript location.pathname using regex to determine pattern below, as you'll notice the word "site" is repeating in this pattern..
http://www.somehost.tv/sitedev/
http://www.somehost.tv/sitetest/
http://www.somehost.tv/site/
http://www.somehost.tv/sitedev/index.html
http://www.somehost.tv/sitetest/index.html
http://www.somehost.tv/site/index.html
I am attempting to display jQuery dialog only and only if the user is at the root of the website.
Simply use the DOM to parse this. No need to invoke a regex parser.
var url = 'http://www.somesite.tv/foobar/host/site';
urlLocation = document.createElement('a');
urlLocation.href = url;
alert(urlLocation.hostname); // alerts 'www.somesite.tv'
A complete pattern, including protocol and domain, could be like this:
/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/
but, if you're matching against location.pathname just try
/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)
If you do not explicitly need a Regular Expression for this
You also could do for example
Fill an array with your urls
Loop over a decreasing substring of
the shortest element.
Comparing it against
the longest element.
Until they match.
var urls = ["http://www.somehost.tv/sitedev/",
"http://www.somehost.tv/sitetest/",
"http://www.somehost.tv/site/",
"http://www.somehost.tv/sitedev/index.html",
"http://www.somehost.tv/sitetest/index.html",
"http://www.somehost.tv/site/index.html"]
function getRepeatedSub(arr) {
var srt = arr.concat().sort();
var a = srt[0];
var b = srt.pop();
var s = a.length;
while (!~b.indexOf(a.substr(0, s))) {
s--
};
return a.substr(0, s);
}
console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site
Heres an example on JSBin
Given a string with URLs in the following formats:
https://www.cnn.com/
http://www.cnn.com/
http://www.cnn.com/2012/02/16/world/american-nicaragua-prison/index.html
http://edition.cnn.com/?hpt=ed_Intl
W JS/jQuery, how can I extract from the string just cnn.com for all of them? Top level domain plus extension?
Thanks
var loc = document.createElement('a');
loc.href = 'http://www.cnn.com/2012/02/16/world/index.html';
window.alert(loc.hostname); // alerts "cnn.com"
Credits for the previous method:
Creating a new Location object in javascript
function domain(input){
var matches,
output = "",
urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec(input);
if(matches !== null){
output = matches[1];
}
return output;
}
Given that there are top-level domains with dots in them, for example "co.uk", there's no way to do this programatically unless you include a list of all of the TLDs with dots in them.
var domain = location.host.split('.').slice(-2);
If you want it reassembled:
var domain = location.host.split('.').slice(-2).join('.');
But this won't work with co.uk or something. There's no hard nor fast rule for this, not even regex will determine that.
// something.domain.com -> domain.com
function getDomain() {
return window.location.hostname.replace(/([a-z]+.)/,"");
}