Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Created April 28, 2022 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatsuyasusukida/935c7d58609240e96bd8960a81b555b7 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/935c7d58609240e96bd8960a81b555b7 to your computer and use it in GitHub Desktop.
JavaScript padStart alternative
if (require.main === module) {
main()
}
async function main () {
try {
const value = 1234
const str = value.toString(16)
const expected = '0x' + str.padStart(4, '0')
const step1 = '000' + str // <1>
const step2 = step1.slice(-4) // <2>
const step3 = '0x' + step2 // <3>
const actual = step3
// const actual = '0x' + ('000' + str).slice(-4)
console.log({expected, actual})
} catch (err) {
console.error(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment