5

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 ?

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Fuxi
  • 7,501
  • 24
  • 90
  • 138

4 Answers4

8

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

Erikk Ross
  • 2,175
  • 13
  • 18
  • Simple and clean, for global flag add use it like css.replace(/https?:\/\/[^\/]+/ig, ""); @Erikk-ross, can you please add http and global support to it? – Ajay Suwalka Oct 10 '17 at 13:25
  • I would do `css = css.replace(/(https?:)?\/\/[^\/]+/i, "");`, because a `//` prefix means use protocol-relative URL (the browser decides whether to use HTTP or HTTPS according to the current used protocol of the main page). – Michael Litvin Feb 07 '20 at 18:54
1

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"

Sindre Sorhus
  • 62,461
  • 37
  • 161
  • 226
0

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.

FallenRayne
  • 134
  • 4
-2
css = css.replace('http://www.mydomain.com', '');
Erikk Ross
  • 2,175
  • 13
  • 18