Skip to content

Instantly share code, notes, and snippets.

@o-az
Created June 16, 2024 15:43
Show Gist options
  • Save o-az/3a141c98e75a1766b2c450142e8b29be to your computer and use it in GitHub Desktop.
Save o-az/3a141c98e75a1766b2c450142e8b29be to your computer and use it in GitHub Desktop.
GitHub username regex
/**
* Run with `node github-username-regex.mjs` or `npx tsx github-username-regex.mjs`
*/
import assert from 'node:assert'
const pattern = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(-?)?$/i
const cases = [
{ value: "", valid: false },
{ value: "u", valid: true },
{ value: "valid-username", valid: true },
{ value: "Valid-Username", valid: true },
{ value: "-invalid-username", valid: false },
{ value: "valiD-Old-Username-", valid: true },
{ value: "invalid-username--", valid: false },
{ value: "Valid-Username-123-456", valid: true },
{ value: "testingusername01testingusername01testi", valid: true },
]
for(const testCase of cases) {
const valid = pattern.test(testCase.value)
assert.strictEqual(valid, testCase.valid, `Value: ${testCase.value}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment