Last active
November 14, 2025 17:07
-
-
Save sclark39/9daf13eea9c0b381667b61e3d2e7bc11 to your computer and use it in GitHub Desktop.
Convert from Instagram Shortcode to Id and Back using big-integer
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
| var bigint = require( 'big-integer' ) | |
| var lower = 'abcdefghijklmnopqrstuvwxyz'; | |
| var upper = lower.toUpperCase(); | |
| var numbers = '0123456789' | |
| var ig_alphabet = upper + lower + numbers + '-_' | |
| var bigint_alphabet = numbers + lower | |
| function toShortcode( longid ) | |
| { | |
| var o = bigint( longid ).toString( 64 ) | |
| return o.replace(/<(\d+)>|(\w)/g, (m,m1,m2) => | |
| { | |
| return ig_alphabet.charAt( ( m1 ) | |
| ? parseInt( m1 ) | |
| : bigint_alphabet.indexOf( m2 ) ) | |
| }); | |
| } | |
| function fromShortcode( shortcode ) | |
| { | |
| var o = shortcode.replace( /\S/g, m => | |
| { | |
| var c = ig_alphabet.indexOf( m ) | |
| var b = bigint_alphabet.charAt( c ) | |
| return ( b != "" ) ? b : `<${c}>` | |
| } ) | |
| return bigint( o, 64 ).toString( 10 ) | |
| } | |
| toShortcode( '908540701891980503' ) // s.b. 'ybyPRoQWzX' | |
| fromShortcode( 'ybyPRoQWzX' ) // s.b. '908540701891980503' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a simpler way to do the decode part using built-in BigInt and Base64URL handling. This is typescript but you can easily remove the types if you want.
and a bonus of extracting the timestamp in milliseconds
implementing the encode should be pretty straightforward using the same approach.