본문 바로가기
알고리즘/Codewars

[Codewars] Convert string to camel case (6 kyu) / JavaScript

by fluss 2022. 10. 5.

https://www.codewars.com/kata/517abf86da9663f1d2000003

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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"

 

설명:

대시/밑줄로 구분된 단어를 낙타 표기법으로 바꾸는 매서드/함수를 완성하세요. 출력된 문장에서 첫 번째 단어는 원래 단어가 대문자인 경우에만 대문자로 표시되어야 합니다. (쌍봉낙타 표기법, 흔히 파스칼 표기법으로도 불린다.)

 

예시

"the-stealth-warrior"가 "theStealthWarrior"로 변환됩니다.
"The_Stealth_Warrior"가 "TheStealthWarrior"로 변환됩니다.

 

해설

function toCamelCase(str){
  str = str.replace(/-/g, '_').split('_');
  for(let i = 1; i < str.length; i++){
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
  }
  return str.join('');
}

대시나 밑줄로 단어가 구분되기 때문에 대시를 모두 밑줄로 바꿔주고 밑줄을 기준으로 단어를 나누어주었다. 이때 replace('-', '_')로 하면 가장 처음에 있는 대시만 밑줄로 바뀌기 때문에 전체 문자열을 탐색해서 모든 일치를 반환하는 g를 사용해 모든 대시를 밑줄로 바꿔주었다. 그리고 첫 번째 단어는 원래 단어가 대문자일 때만 대문자로 표시하는 것이므로 i를 1로 시작해 두 번째 단어부터 첫 글자를 대문자로 바꿔준다.

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Regular_Expressions

 

정규 표현식 - JavaScript | MDN

정규 표현식, 또는 정규식은 문자열에서 특정 문자 조합을 찾기 위한 패턴입니다. JavaScript에서는 정규 표현식도 객체로서, RegExp의 exec()와 test() 메서드를 사용할 수 있습니다. String의 match(), matchA

developer.mozilla.org

https://www.delftstack.com/ko/howto/javascript/how-to-capitalize-the-first-letter-of-a-string-in-javascript/

 

JavaScript에서 문자열의 첫 글자를 캡틸 라이즈하는 방법

JavaScript에서 문자열의 첫 글자를 대문자로 만드는 다양한 방법을 보여줍니다.

www.delftstack.com

 

댓글