I'm accessing the stylesheet collection like this:
var css = document.styleSheets[0];
It returns eg. http://www.mydomain.com/css/main.css
Question: how can I strip the domain name to just get /css/main.css
?
I'm accessing the stylesheet collection like this:
var css = document.styleSheets[0];
It returns eg. http://www.mydomain.com/css/main.css
Question: how can I strip the domain name to just get /css/main.css
?
This regular expression should do the trick. It will replace any domain name found with an empty string. Also supports https://
//css is currently equal to http://www.mydomain.com/css/main.css
css = css.replace(/https?:\/\/[^\/]+/i, "");
This will return /css/main.css
You can use a trick, by creating a <a>
-element, then setting the string to the href of that <a>
-element and then you have a Location object you can get the pathname from.
You could either add a method to the String prototype:
String.prototype.toLocation = function() {
var a = document.createElement('a');
a.href = this;
return a;
};
and use it like this:
css.toLocation().pathname
or make it a function:
function toLocation(url) {
var a = document.createElement('a');
a.href = url;
return a;
};
and use it like this:
toLocation(css).pathname
both of these will output: "/css/main.css"
How about:
css = document.styleSheets[0];
cssAry = css.split('/');
domain = cssAry[2];
path = '/' + cssAry[3] + '/' + cssAry[4];
This technically gives you your domain and path.
URL.replace(/\S{0,6}\/\/[a-zA-Z0-9\-_.]*\//, '')
strips the domain part identified by:
let URL = 'http://www.example.com/css/main.css'
document.write (URL.replace(/\S{0,6}\/\/[a-zA-Z0-9\-_.]*/, '') +'<br>')
URL = 'upTo5://www.example.com/css/main.css'
document.write (URL.replace(/\S{0,6}\/\/[a-zA-Z0-9\-_.]*/, '') +'<br>')
URL = 'http://a-zA-Z0-9-_.upToSlash/css/main.css'
document.write (URL.replace(/\S{0,6}\/\/[a-zA-Z0-9\-_.]*/, '') +'<br>')
URL = '//www.example.com/css/main.css'
document.write (URL.replace(/\S{0,6}\/\/[a-zA-Z0-9\-_.]*/, '') +'<br>')
//Protocol, e.g. 'http' may be omitted in cases, where it default automatically.
//Commonly in links, where the URL is known, but SSL/TLS support of target site is not.