我想分割https://abcnews.go.com/
这种类型的URL。
想要获得abcnews
我用了:
.split('//')[1]
.split('www.')[1]
.split('.com')[0]
.split('.org')[0]
.split('.edu')[0]
.split('.info')[0]
我得到错误无法拆分。
知道怎么做吗?
这看起来很安全:
(?:https?:\/\/(?:www\.)?|www\.)([^.\/]+)
见证明。
解释
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
http 'http'
--------------------------------------------------------------------------------
s? 's' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
www 'www'
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
www 'www'
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^.\/]+ any character except: '.', '\/' (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
JavaScript代码:
const url = "https://abcnews.go.com/"
const regex = /(?:https?:\/\/(?:www\.)?|www\.)([^.\/]+)/
const match = url.match(regex)
if (match) {
console.log(match[1])
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句