문장은 공백으로 연결된 문자열(단어라고 함)을 포함하는 문자열일 뿐입니다. 우리는 그러한 문장 문자열 하나를 취하고 문자열의 마지막 단어에서 두 번째 단어의 문자 수를 계산하는 JavaScript 함수를 작성해야 합니다. 문자열이 2개 이하의 단어를 포함하는 경우 함수는 0을 반환해야 합니다.
예를 들어 -
입력 문자열이 -
인 경우const str = 'this is an example string';
그러면 출력은 다음과 같아야 합니다. -
const output = 7;
예의 문자 수가 7이기 때문입니다.
예시
다음은 코드입니다 -
const str = 'this is an example string';
const countSecondLast = (str = '') => {
const strArr = str.split(' ');
const { length: len } = strArr;
if(len <= 2){
return 0;
};
const el = strArr[len - 2];
const { length } = el;
return length;
};
console.log(countSecondLast(str)); 출력
다음은 콘솔 출력입니다 -
7