I have an input field and my users are entering their instagram username in various formats
JavaScript
x
5
1
@username
2
https://www.instagram.com/username
3
https://www.instagram.com/username/
4
instagram.com/username
5
how can I extract username only?
with
JavaScript
1
2
1
(?:(?:http|https)://)?(?:www.)?(?:instagram.com|instagr.am)/([A-Za-z0-9-_]+)
2
I can extract from the URL. not sure how to search for whatever is after @
Advertisement
Answer
You want a regex that matches either @
or various forms of the URL version as a prefix to the username, followed by an optional forward-slash.
Something like this
JavaScript
1
2
1
/^(?:@|(?:https?://)?(?:www.)?instagr(?:.am|am.com)/)?(w+)/?$/
2
Breaking it down
JavaScript
1
13
13
1
^
2
(?:
3
@ - literal "@"
4
| - or
5
(?:https?://)? - optional HTTP / HTTPS scheme
6
(?:www.)? - optional "www."
7
instagr(?:.am|.com) - "instagram.com" or "instgr.am"
8
/ - forward-slash
9
)? - the whole prefix is optional
10
(w+) - capture group for the username. Letters, numbers and underscores
11
/? - optional trailing slash
12
$
13
JavaScript
1
17
17
1
const inputs = [
2
'@username',
3
'https://www.instagram.com/username',
4
'https://www.instagram.com/username/',
5
'instagram.com/username',
6
'handsome_jack',
7
'http://example.com/handsome'
8
]
9
10
const rx = /^(?:@|(?:https?://)?(?:www.)?instagr(?:.am|am.com)/)?(w+)/?$/
11
12
inputs.forEach(input => {
13
let match = rx.exec(input)
14
if (match) {
15
console.log(input, match[1])
16
}
17
})