[프로그래머스 2레벨] JadenCase 문자열 만들기

이민선(Jasmine)·2023년 1월 8일
1
post-thumbnail

나의 코드

function solution(s) {
    const arr = s.split(' ');
    const res = arr.map((v) => v.split('').map((w,i)=> i === 0 ? w.toUpperCase() : w.toLowerCase()).join(''));
    return res.join(' ')
}

받은 문자열을 띄어쓰기 단위의 배열로 쪼개고,
각 배열 원소의 첫 단어이면 대문자, 그 외에는 소문자로 변환했다. 이를 위해 map 안에 map을 사용했다.
모두 변환해준 후 문자열을 반환해야 하므로 다시 join하기!

프로그래머스 문제들을 풀면서 어느샌가부터 map무새가 되었다. (한 때 for문 무새였지만 나름 진화함 ㅋㅋㅋㅋ) 물론 map도 매우매우 유용하고 간결하고 아름답지만, 이 문제처럼 map 안에서 map을 또 쓰는 것보다 더욱 간편한 방법도 있다.

String 메서드를 적극 이용하자.

function solution(s) {
    const arr = s.split(' ');
    const res = arr.map((v) => v.charAt(0).toUpperCase() + v.substring(1).toLowerCase());
    return res.join(' '); 
}

str.charAt(index)

주어진 문자열 str에서 index번째 글자를 반환.

MDN 참고:
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

str.substring(indexStart[, indexEnd])

주어진 문자열 str에서 indexStart번째 글자부터 indexEnd개의 글자를 반환.
indexEnd 생략 시 끝까지 다 반환.

MDN 참고:
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

이 코드에서는 각 배열원소의 첫번째 글자를 대문자로 나타낼 때 charAt(0)을 사용했고, 첫번째 글자 외의 글자들은 substring(1)로 표현한 것이다.

String 메서드 핵꿀팁! 앞으로도 자주 이용하자 ^^

profile
기록에 진심인 개발자 🌿

0개의 댓글