gpt4 book ai didi

javascript - 如何从字符串中提取Instagram用户名

转载 作者:行者123 更新时间:2023-12-05 01:36:01 25 4
gpt4 key购买 nike

我有一个输入字段,我的用户正在以各种格式输入他们的 instagram 用户名

@username
https://www.instagram.com/username
https://www.instagram.com/username/
instagram.com/username

我怎样才能只提取用户名

(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)

我可以从 URL 中提取。不知道如何搜索@之后的任何内容

最佳答案

您需要一个匹配 @ 或各种形式的 URL 版本的正则表达式作为用户名的前缀,后跟可选的正斜杠。

类似的东西

/^(?:@|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/

打破它

^
(?:
@ - literal "@"
| - or
(?:https?:\/\/)? - optional HTTP / HTTPS scheme
(?:www\.)? - optional "www."
instagr(?:\.am|\.com) - "instagram.com" or "instgr.am"
\/ - forward-slash
)? - the whole prefix is optional
(\w+) - capture group for the username. Letters, numbers and underscores
\/? - optional trailing slash
$

const inputs = [
'@username',
'https://www.instagram.com/username',
'https://www.instagram.com/username/',
'instagram.com/username',
'handsome_jack',
'http://example.com/handsome'
]

const rx = /^(?:@|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/

inputs.forEach(input => {
let match = rx.exec(input)
if (match) {
console.log(input, match[1])
}
})

关于javascript - 如何从字符串中提取Instagram用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61883196/

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