Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Today
Total
관리 메뉴

고리타분한 개발자

SentenceCapitalization 본문

JavaScript/Algorithm

SentenceCapitalization

sunlee334 2018. 5. 12. 01:00

목적


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


example


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


들어가기에 앞서


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. 




function capitalize(str) {
const words = []

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

return words.join(' ')
}


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
}
















'JavaScript > Algorithm' 카테고리의 다른 글

Fizz Buzz  (0) 2018.05.12
Integer Reversal  (0) 2018.05.12
Paldinromes  (0) 2018.05.12
Max Char  (0) 2018.05.12
String Reversal  (0) 2018.05.12
Comments