Javascript简单的正则表达式找到根域

时间:2013-02-11 07:43:05

标签: javascript regex

我有一个使用正则表达式返回给定网址的根域的函数。

http://jsfiddle.net/hSpsT/

function cleanUp(url) {
  url = url.replace(new RegExp(/^\s+/),""); // START
  url = url.replace(new RegExp(/\s+$/),""); // END

  // IF FOUND, CONVERT BACK SLASHES TO FORWARD SLASHES
  url = url.replace(new RegExp(/\\/g),"/");

  // IF THERE, REMOVES 'http://', 'https://' or 'ftp://' FROM THE START
  url = url.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");

  // IF THERE, REMOVES 'www.' FROM THE START OF THE STRING
  url = url.replace(new RegExp(/^www\./i),"");
  //remove slash from end
  url = url.replace(new RegExp(/\/$/i),"");    
  return url;
}

但它使用多重正则表达式,我们担心性能。有没有更好的方法在一行正则表达式中做同样的事情?

注意:

document.location.host在我的案例中似乎不起作用。

2 个答案:

答案 0 :(得分:5)

Extract hostname name from string

尝试:

function cleanUp(url) {
    var url = $.trim(url);
    if(url.search(/^https?\:\/\//) != -1)
        url = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i, "");
    else
        url = url.match(/^([^\/?#]+)(?:[\/?#]|$)/i, "");
    return url[1];
}

alert(cleanUp('  http://www.google.com/about.html'));
alert(cleanUp('  www.google.com/about.html'));

答案 1 :(得分:1)

试试这个:

http://jsfiddle.net/picklespy/gb34u/1/

适用于所有现代浏览器,甚至适用于IE 5.5 +。

var url = document.createElement('a');
url.href = 'http://maps.test.google.com';
var host = url.hostname;

host = host.split('.');

var domain = host.pop();
domain = host.pop() + '.' + domain;

alert('Root is: ' + domain)