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
1.0k views
in Technique[技术] by (71.8m points)

extract domain name from url javascript

I'm trying to extract domain name from string in 'tweets', how can I avoid to extract double backward slashes from string? the regular expression I have defined in let url

let tweets = [
  "Thank you to the Academy and the incredible cast & crew of #TheRevenant. #Oscars",
  "@HardingCompSci department needs student volunteers for #HourOfCode https://hourofcode.com/us",
  "Checkout the most comfortable earbud on #Kickstarter and boost your #productivity https://www.kickstarter.com/",
  "Curious to see how #StephenCurry handles injury. http://mashable.com/2016/04/25/steph-curry-knee-injury-cries-cried/"
];


let url = ///.+?.com?/;

tweets.forEach(function(tweet) {
  console.log(url.exec(tweet));
});

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

1 Reply

0 votes
by (71.8m points)

Use a Capturing Group

A part of a pattern can be enclosed in parentheses (...). This is called a “capturing group”.

That has two effects:

It allows to get a part of the match as a separate item in the result array. If we put a quantifier after the parentheses, it applies to the parentheses as a whole.

In your code you have let url = ///.+?.com?/;

You are only interested in the part following the 2 slashes, so make a capturing group for that by enclosing it in braces: let url = ///(.+?.com?)/;

Then change the code in the loop a bit to get the result from the first capturing group and you end up with:

let tweets = [
  "Thank you to the Academy and the incredible cast & crew of #TheRevenant. #Oscars",
  "@HardingCompSci department needs student volunteers for #HourOfCode https://hourofcode.com/us",
  "Checkout the most comfortable earbud on #Kickstarter and boost your #productivity https://www.kickstarter.com/",
  "Curious to see how #StephenCurry handles injury. http://mashable.com/2016/04/25/steph-curry-knee-injury-cries-cried/"
];


let url = ///(.+?.com?)/;

tweets.forEach(function(tweet) {
  var match = url.exec(tweet)
  console.log(match && match[1] || match);
});

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

...