문자열 my_string이 매개변수로 주어질 때, 대문자는 소문자로 소문자는 대문자로 변환한 문자열을 return하도록 solution 함수를 완성해주세요.
function solution(my_string) {
const answer = my_string.replace(/./g, (s) => {
return s === s.toUpperCase() ? s.toLowerCase() : s.toUpperCase();
});
return answer;
}
정규표현식을 사용했다.
/./
: 모든 문자를 가르킴g
: 패턴과 일치하는 모든 것들을 찾음.// g 유무에 따른 결과값 차이 solution('cccCCC'); // g를 붙였을 때 결과 : CCCccc // g를 붙이지 않을 때 결과: CccCCC
function solution(my_string) {
var answer = '';
for (let c of my_string)
answer += c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase();
return answer;
}
반복문을 사용해 대소문자를 바꾸며 새로운 변수에 값을 추가시켰다.
function solution(my_string) {
return my_string.split('').map(n => n === n.toUpperCase() ? n.toLowerCase() : n.toUpperCase()).join('')
}
문자열을 배열로 바꾼 뒤 map()을 활용했다.
map()
: 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환// 사용법 arr.map(callback(currentValue[, index[, array]])[, thisArg])
이후
join()
을 사용해 배열의 모든 요소를 연결하여 하나의 문자열로 만들어주었다.