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

JavaScript를 사용하여 주어진 문장에서 대문자로 된 단어를 찾고 그 앞에 문자를 추가하는 방법은 무엇입니까?

<시간/>

다음과 같이 대문자로 된 영어 알파벳이 포함된 문자열이 있다고 가정해 보겠습니다. -

const str = "Connecting to server Connection has been successful We found result";

우리는 그러한 문자열 하나를 받아서 문자열의 모든 대문자 앞에 공백 앞에 쉼표 ','를 삽입하는 JavaScript 함수를 작성해야 합니다.

이에 대한 코드는 -

const str = "Connecting to server Connection has been successful We found
result";
const capitaliseNew = str => {
   let newStr = '';
   const regex = new RegExp(/.[A-Z]/g);
   newStr = str.replace(regex, ',$&');
   return newStr;
};
console.log(capitaliseNew(str));

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

Connecting to server, Connection has been successful, We found result