Detail
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples
"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"
<code>
function toCamelCase(str) {
const newArray = str.split(/[_]|[-]/); //-와 _ 에 맞게 배열로 자르기
const toUpperString = "";
//console.log(newArray);
//여기서 두번째 newArra의 첫번째 단어를 대문자로
newArray.map((a, i) => {
if (i > 0) {
let result = a.split(""); //한단어씩 자르기
let SliceResult = result.slice(1); //첫단어 slice하기
let UpperJoin = [result[0].toUpperCase(), ...SliceResult];
//첫단어를 대문자로 바꾼 것과 기존 문자 합치기
toUpperString += UpperJoin.join(""); //map함수 안에 있기에 하나씩 결과가 나옴. 이를 합쳐줌
}
});
const totalResult = newArray[0] + toUpperString; //기존에 첫단어와 대문자로 바꿔준 단어를 합침
console.log(totalResult);
return totalResult
}
//test
//toCamelCase("the_stealth_warrior");
//toCamelCase("The-Stealth-Warrior");
//toCamelCase("A-B-C")
<other>
function toCamelCase(str){
var regExp=/[-_]\w/ig;
return str.replace(regExp,function(match){
return match.charAt(1).toUpperCase();
});
}
* charAt() 함수는 문자열에서 특정 인덱스에 위치하는 유니코드 단일문자를 반환
function toCamelCase(str){
return str.split(/-|_/g).map((w, i) => (i > 0 ? w.charAt(0).toUpperCase() : w.charAt(0)) + w.slice(1)).join('');
}
다른 사람 코드 분석 결과,,
내 코드는 정말 더럽다는 걸 다시한번 느꼈다 😓😭
클린 코드가 시급!!!!!
'Algorithm > Codewars' 카테고리의 다른 글
[Codewars/JS] Convert string to camel case (0) | 2022.01.30 |
---|---|
[Codewars/JS] Disemvowel Trolls (0) | 2022.01.21 |
[Codewars/JS] Find the odd int (0) | 2022.01.20 |
[Codewars/JS] Vowel Count (0) | 2022.01.18 |
[Codewars/JS] Moving Zeros To The End (0) | 2022.01.14 |