DEV Community

Discussion on: Web Basics: How to Capitalize a Word in JavaScript

Collapse
 
qm3ster profile image
Mihail Malo

TextDecoder solution:

{
  const encoder = new TextEncoder()
  const decoder = new TextDecoder()
  const capitalizeASCIIalphanum = str => {
    const arr = encoder.encode(str)
    const len = arr.length
    let val = arr[0]
    if (val > 0x60) arr[0] = val - 0x20
    for (let i = 1; i < len; i++) {
      val = arr[i]
      if (val < 0x5b) arr[i] = val + 0x20
    }
    return decoder.decode(arr)
  }


  const { log } = console
  log(capitalizeASCIIalphanum("hello"))
  log(capitalizeASCIIalphanum("GREAT"))
  log(capitalizeASCIIalphanum("aWESOME"))
}

Many checks are missing. This is intentional, because we are going to pretend that this is performant.