Strip domain name from url (string)

I access the collection of style sheets as follows:

var css = document.styleSheets[0]; 

Returns, for example. http://www.mydomain.com/css/main.css

Question: how can I delete a domain name to just get /css/main.css ?

+4
source share
4 answers

This regex 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

+7
source

You can use the trick by creating <a> -element, then setting the line to href of this <a> element, and then you have a Location Object you can get the path name.

You can 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 as follows:
css.toLocation().pathname

or make it a function:

 function toLocation(url) { var a = document.createElement('a'); a.href = url; return a; }; 

and use it as follows:
toLocation(css).pathname

both of them will output: "/css/main.css"

+1
source

What about:

 css = document.styleSheets[0]; cssAry = css.split('/'); domain = cssAry[2]; path = '/' + cssAry[3] + '/' + cssAry[4]; 

This technically gives you your domain and path.

0
source
 css = css.replace('http://www.mydomain.com', ''); 
-1
source

Source: https://habr.com/ru/post/1306320/


All Articles