简体   繁体   English

node.js-如何提取两个斜杠之间的子字符串?

[英]node.js - How to extract a substring between 2 slashes?

I need to extract the domain name from a string which is like " http://www.domain.com/bla324 ". 我需要从类似“ http://www.domain.com/bla324 ”的字符串中提取域名。 The result should be "www.domain.com". 结果应为“ www.domain.com”。

Any ideas on this? 有什么想法吗?

You can simply use a regular expression : 您可以简单地使用一个正则表达式:

var url = "http://www.domain.com/bla324",
    match = url.match(/\/\/([^\/]+)\//)[1];
if (match) {
    var host = match[1];
    ...
}

You may also use the dedicated and standard node package url : 您也可以使用专用和标准节点包url

var url = "http://www.domain.com/bla324",
    urlObject = require('url').parse(url),
    host = urlObject.host;

In the browser, I would use the a element : 在浏览器中,我将使用a元素:

var url = "http://www.domain.com/bla324",
    a = document.createElement('a');
a.href = url;
var host = a.host;

In node, the package url like @dystroy said. 在节点中,包url如@dystroy所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM