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

문자열의 단어 바꾸기 - JavaScript

<시간/>

문자열을 가져와서 해당 문자열의 인접 단어를 바꾸는 JavaScript 함수를 작성해야 합니다.

예:입력 문자열이 -

인 경우
const str = "This is a sample string only";

그러면 출력은 다음과 같아야 합니다. -

"is This sample a only string"

이 함수의 코드를 작성해 봅시다 -

예시

다음은 코드입니다 -

const str = "This is a sample string only";
const replaceWords = str => {
   return str.split(" ").reduce((acc, val, ind, arr) => {
      if(ind % 2 === 1){
         return acc;
      }
      acc += ((arr[ind+1] || "") + " " + val + " ");
      return acc;
   }, "");
};
console.log(replaceWords(str));

출력

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

is This sample a only string