从绝对网址获取亲戚

时间:2014-10-07 12:38:36

标签: javascript

我是新手,如果这个问题很愚蠢或很容易,那就很抱歉。 我有一个包含绝对URL的字符串变量。我想从中提取相对网址。 示例:http://something.com/fizz/buzz => /香味/蜂鸣

我需要使用一个库,还是应该编写自己的字符串操作函数?如果是后者,我应该去regexp吗?

编辑:这是最好的做法吗?还是我需要写自己的黑客?

2 个答案:

答案 0 :(得分:3)

这适用于http://something.com/fizz/buzz以及something.com/fizz/buzz

function getRelativeURL(the_url)
{
    // remove the :// and split the string by '/'
    var the_arr = the_url.replace('://','').split('/');

    // remove the first element (the domain part)
    the_arr.shift();

    // join again the splitted parts and return them with a '/' preceding
    return( '/'+the_arr.join('/') );
}

在此处查看此操作: http://jsfiddle.net/3s15sbun/

答案 1 :(得分:0)

您可以在链接上使用pathname

  

HTMLHyperlinkElementUtils.pathname属性是USVString   包含一个首字母' /'后跟URL的路径。

function getUrlPath(url) {
  var a = document.createElement('a');
  a.href = url;
  return a.pathname;
}
getUrlPath("http://something.com/fizz/buzz"); // "/fizz/buzz"