gpt4 book ai didi

javascript - 从 url javascript 中提取域名

转载 作者:行者123 更新时间:2023-12-04 03:43:06 36 4
gpt4 key购买 nike

我正在尝试从“tweets”中的字符串中提取域名,如何避免从字符串中提取双反斜杠?我在 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));
});

最佳答案

使用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.

在你的代码中你有 let url =/\/\/.+?\.com?/;

您只对 2 个斜线之后的部分感兴趣,因此通过将其括在大括号中来为其创建一个捕获组:let url =/\/\/(.+?\.com?)/;

然后稍微更改循环中的代码以从第一个捕获组中获取结果,最终得到:

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);
});

关于javascript - 从 url javascript 中提取域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65606524/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com