Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript의 camelCase 문자열에 하이픈 문자열

<시간/>

다음과 같이 하이픈으로 구분된 단어가 포함된 문자열이 있다고 가정합니다. -

const str = 'this-is-an-example';

우리는 그러한 문자열 하나를 받아서 그것을 camelCase 문자열로 변환하는 JavaScript 함수를 작성해야 합니다.

위 문자열의 경우 출력은 -

여야 합니다.
const output = 'thisIsAnExample';

이에 대한 코드는 -

const str = 'this-is-an-example';
const changeToCamel = str => {
   let newStr = '';
   newStr = str
   .split('-')
   .map((el, ind) => {
      return ind && el.length ? el[0].toUpperCase() + el.substring(1)
      : el;
   })
   .join('');
   return newStr;
};
console.log(changeToCamel(str));

다음은 콘솔의 출력입니다 -

thisIsAnExample