从url中删除域名(字符串)

我正在访问样式表集合,如下所示:

var css = document.styleSheets[0]; 

它返回例如。 http://www.mydomain.com/css/main.css

问题:如何删除域名以获取/css/main.css

这个正则表达式应该可以解决问题。 它将替换使用空字符串找到的任何域名。 还支持https://

 //css is currently equal to http://www.mydomain.com/css/main.css css = css.replace(/https?:\/\/[^\/]+/i, ""); 

这将返回/css/main.css

您可以使用技巧,通过创建 -element,然后将字符串设置为该 -element的href,然后您有一个Location对象,您可以从中获取路径名。

您可以向String原型添加方法:

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

并像这样使用它:
css.toLocation().pathname

或使它成为一个function:

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

并像这样使用它:
toLocation(css).pathname

这两个都输出: "/css/main.css"

怎么样:

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

这在技术上为您提供了域和路径。

 css = css.replace('http://www.mydomain.com', '');