Last active
June 16, 2024 15:46
-
-
Save o-az/9d304e88af9706bcc6d1cc6c3984a2f3 to your computer and use it in GitHub Desktop.
GitHub username regex: /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(-?)?$/i
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import assert from 'node:assert' | |
/** | |
* Run with `node github-username-regex.mjs` or `npx tsx github-username-regex.mjs` | |
*/ | |
/** | |
* 1-39 characters | |
* case insensitive alphanumeric + hyphen | |
* cannot start with hyphen | |
* cannot have consecutive hyphens | |
* cannot end with hyphen for new users, but existing usernames can | |
*/ | |
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
https://regexr.com/81nk2