Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从字符串中提取特定内容_Javascript_Regex_String - Fatal编程技术网

Javascript 如何从字符串中提取特定内容

Javascript 如何从字符串中提取特定内容,javascript,regex,string,Javascript,Regex,String,我有某些URL,例如: http://www.moneycontrol.com/news/business/vistaras-turbulent-takeoffthe-cut-throat-indian-skies_3510081.html http://www.business-standard.com/article/markets/patanjali-ayurved-targets-250-revenue-growth-in-fy16-edelweiss-115100900788_1.ht

我有某些URL,例如:

http://www.moneycontrol.com/news/business/vistaras-turbulent-takeoffthe-cut-throat-indian-skies_3510081.html
http://www.business-standard.com/article/markets/patanjali-ayurved-targets-250-revenue-growth-in-fy16-edelweiss-115100900788_1.html

这些可以是任何网站的URL。如何从内容中提取
www.moneycontrol.com
www.business-standard.com

您基本上需要从url中提取域。您可以通过以下方式获得:

function extractDomain(url) {
    var domain;

    if (url.indexOf("://") > -1) 
        domain = url.split('/')[2];
    else 
        domain = url.split('/')[0];

    return domain.split(':')[0];
}

这可以通过两个
split
函数轻松完成,将字符串拆分为数组

var path = string.split("://")[1].split('/')[0]
这将为您提供一个类似www.moneypath.com的URL

如果您只想获取url名称,请删除
www.
.com
,这两种方法都可以

path.replace(/(www.)|(.com)/g, '')
您还可以再次使用拆分方法

path.split('www.')[1].split('.com')[0]

就个人而言,我更喜欢正则表达式方法,因为它更干净。

看看:
var myDomain=new ParsedUrl(“http://www.moneycontrol.com/news/business/vistaras-turbulent-takeoffthe-cut-throat-indian-skies_3510081.html主持人,
这里是一个不使用拆分的版本:
var domains=url.map(函数(url){var a=document.createElement(“a”);a.href=url;返回a.hostname;})