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

문자열에 배열에 단어가 포함되어 있으면 제거하십시오. JavaScript

<시간/>

문자열과 문자열 배열이 제공됩니다. 우리의 임무는 배열에 있는 모든 부분 문자열을 문자열에서 제거하는 함수를 작성하는 것입니다.

이 부분 문자열은 완전한 단어이므로 두 개의 공백이 함께 나타나지 않도록 선행 또는 후행 공백도 제거해야 합니다.

따라서 이 함수의 코드를 작성해 보겠습니다 -

예시

const string = "The weather in Delhi today is very similar to the weather
in Mumbai";
const words = [
   'shimla','rain','weather','Mumbai','Pune','Delhi','tomorrow','today','yesterday'
];
const removeWords = (str, arr) => {
   return arr.reduce((acc, val) => {
      const regex = new RegExp(` ${val}`, "g");
      return acc.replace(regex, '');
   }, str);
};
console.log(removeWords(string, words));

출력

이 코드의 출력은 -

입니다.
The in is very similar to the in