SentenceCapitalization

Directions

문자열에서 각 단어의 첫글자를 대문자로 변환시키기

Examples

  capitalize('a short sentence') --> 'A Short Sentence'
  capitalize('a lazy fox') --> 'A Lazy Fox'
  capitalize('look, it is working!') --> 'Look, It Is Working!'

TIP

Array.prototype.slice()

const word = 'there'

word[0] // t
word[0].toUpperCaer() // T
word.slice(1) // here

const sentence = 'Hi there buddy!'

sentence.split(' ') // ["Hi", "there", "buddy!"]

1.

SentenceCapitalization_1

function capitalize(str) {
  const words = []

  // 띄어쓰기 한 곳마다 나누기
  for (let word of str.split(' ')) {
    // 단어의 처음 글자를 대문자로 바꾸기
    words.push(word[0].toUpperCase() + word.slice(1))
  }

  return words.join(' ')
}

2.

SentenceCapitalization_2

function capitalize(str) {
  let result = str[0].toUpperCase()

  for (let i = 1; i < str.length; i++) {
    if (str[i - 1] === '') {
      result += str[i].toUpperCase()
    } else {
      result += str[i]
    }
  }

  return result
}

Test

const capitalize = require('./index')

test('Capitalize is a function', () => {
  expect(typeof capitalize).toEqual('function')
})

test('capitalizes the first letter of every word in a sentence', () => {
  expect(capitalize('hi there, how is it going?')).toEqual(
    'Hi There, How Is It Going?'
  )
})

test('capitalizes the first letter', () => {
  expect(capitalize('i love breakfast at bill miller bbq')).toEqual(
    'I Love Breakfast At Bill Miller Bbq'
  )
})