點燈坊

失くすものさえない今が強くなるチャンスよ

Padding Partial String

Sam Xiao's Avatar 2022-12-16

If we want to pad the partial string, we can’t simply use padStart() to get the result.

Version

ECMAScript 2015

padStart()

let s = 'A7'

let f = x => {
  let c = x.substring(0, 1)
  let n = x.substring(1).padStart(2, '0')

  return `${c}${n}`
}

f(s) // ? A07

We want to pad A7 to A07.

  • substring():get the captical letter
  • padStart():pad the remaining string

Conclusion

  • We can’t simply use padStart() to pad partial string, we have to get the capital letter and pad the remaining string

Reference

MDN, String.prototype.substring()
MDN, String.prototype.padStart()