이 글에서는 하나의 문자열과 문자열 배열을 인수로 받는 JavaScript 함수를 작성하는 방법을 알아보겠습니다.
이 함수가 반환해야 할 값은 원본 문장에서 배열에 포함된 단어가 등장하는 모든 위치를 공백으로 치환한 새로운 문자열입니다. 또한 문제 해결에는 반드시 String.prototype.replace() 메서드를 활용해야 합니다.
예제 코드
전체 구현 코드는 다음과 같습니다.
var excludeWords = ["A", "ABOUT", "ABOVE", "ACROSS", "ALL", "ALONG", "AM",
"AN", "AND", "ANY", "ASK", "AT", "AWAY", "CAN", "DID", "DIDN'T", "DO",
"DON'T", "FOR", "FROM", "HAD", "HAS", "HER", "HIS", "IN", "INTO", "IS",
"IT", "NONE", "NOT", "OF", "ON", "One", "OUT", "SO", "SOME", "THAT",
"THE", "THEIR", "THERE", "THEY", "THESE", "THIS", "TO", "TWIT", "WAS",
"WERE", "WEREN'T", "WHICH", "WILL", "WITH", "WHAT", "WHEN", "WHY"];
var sentence = "The first solution does not work for any UTF-8 alphaben. I have managed to create function which do not use RegExp and use good UTF-8 support in JavaScript engine. The idea is simple if symbol is equal in uppercase and lowercase it is special character. The only exception is made for whitespace.";
const removeExcludedWords = (str, words) => {
let sentence = '';
const regex = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');
sentence = str.replace(regex, "");
return sentence;
};
console.log(removeExcludedWords(sentence, excludeWords));실행 결과
위 코드를 실행하면 콘솔에 다음과 같은 결과가 출력됩니다.
first solution does work UTF-8 alphaben. I have managed create function use RegExp use good UTF-8 support JavaScript engine. idea simple if symbol equal uppercase lowercase special character. only exception made whitespace.
코드 동작 원리
핵심 로직은 removeExcludedWords 함수 내부에서 정규식을 동적으로 생성하는 부분입니다.
- words.join('|') — 배열에 담긴 모든 단어를 파이프(|) 기호로 연결해 "A|ABOUT|ABOVE..." 형태의 선택 패턴을 만듭니다.
- \b (단어 경계) — 단어의 시작과 끝을 정확히 인식하여, 예를 들어 "AN"이 "banana"처럼 다른 단어의 일부와 잘못 매칭되는 상황을 방지합니다.
- 'gi' 플래그 — g(global) 플래그는 일치하는 모든 항목을 대상으로 하고, i(ignoreCase) 플래그는 대소문자를 구분하지 않고 매칭하도록 합니다.
이렇게 만든 정규식을 replace() 메서드에 적용하면 제외 목록에 있는 단어들이 빈 문자열(" ")로 치환되어 문장에서 자연스럽게 사라집니다. 단어를 완전히 삭제하지 않고 공백 한 칸만 남기고 싶다면 두 번째 인수를 "" 대신 " "로 바꿔주면 됩니다.