javascript - 如何从字符串中提取Instagram用户名
问题描述
我有一个输入字段,我的用户正在以各种格式输入他们的 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])
}
})
推荐阅读
- python - 如何调整 QMovie 的大小?
- php - 未找到接口“Ratchet\MessageComponentInterface”
- typescript - 消除未定义的警告?来自 Object.entries 遍历的值应该是保证字符串
- html - 用ul li在html中将表格单元格组合在一起?
- javascript - 为什么 JavaScript 提示无法正常工作?
- c++ - 为什么不显示版本信息
- sql - 检查项目是否有数据
- arrays - Numpy savetxt 文件位置
- excel - 有条件的复制粘贴excel vba
- github - github 从特定日期范围内获取用户合并的代码行