Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 从字符串中提取主机名(Extract hostname name from string)

I would like to match just the root of a URL and not the whole URL from a text string.

(我想只匹配URL的根,而不匹配文本字符串中的整个URL。)

Given:

(鉴于:)

http://www.youtube.com/watch?v=ClkQA2Lb_iE
http://youtu.be/ClkQA2Lb_iE
http://www.example.com/12xy45
http://example.com/random

I want to get the 2 last instances resolving to the www.example.com or example.com domain.

(我想将最后2个实例解析为www.example.comexample.com域。)

I heard regex is slow and this would be my second regex expression on the page so If there is anyway to do it without regex let me know.

(我听说正则表达式很慢,这将是我在页面上的第二个正则表达式表达式,因此,如果仍然需要不使用正则表达式,请告诉我。)

I'm seeking a JS/jQuery version of this solution.

(我正在寻找此解决方案的JS / jQuery版本。)

  ask by Chamilyan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A neat trick without using regular expressions:

(一个不使用正则表达式的巧妙技巧:)

var tmp        = document.createElement ('a');
;   tmp.href   = "http://www.example.com/12xy45";

// tmp.hostname will now contain 'www.example.com'
// tmp.host will now contain hostname and port 'www.example.com:80'

Wrap the above in a function such as the below and you have yourself a superb way of snatching the domain part out of an URI.

(将上面的内容包装在下面的功能中,您将拥有一种从URI中抢夺域部分的绝妙方式。)

function url_domain(data) {
  var    a      = document.createElement('a');
         a.href = data;
  return a.hostname;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...