Skip to content

how to extract instagram username from string

I have an input field and my users are entering their instagram username in various formats

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

how can I extract username only?

with

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

I can extract from the URL. not sure how to search for whatever is after @

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

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

Breaking it down

^
(?:
  @                     - 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]) 
  }
})