Search Input에 특정 단어를 검색했을 때 검색된 단어를 하이라이팅 하는 방법
g = global, match all instances of the pattern in a string, not just one.i = case-insensitive (so, for example, /a/i will match the string "a" or "A".따라서 new RegExp(`(${query})`, 'gi') 처럼 작성한다면, queried text가 여러개 존재할 경우, 모든 queried text를 포함하고, 대문자와 소문자 모두 하이라이팅을 하게 된다.
html에서 기본적으로 제공하는 mark태그가 있다. 텍스트 하이라이팅을 하기 위해서 mark태그를 사용하거나, 따로 원하는 색상으로 하이라이팅을 하고 싶다면 span태그를 사용하면 된다.
const highlightedText = (text, query) => {
if (query !== '' && text.includes(query)) {
const parts = text.split(new RegExp(`(${query})`, 'gi'));
return (
<>
{parts.map((part, index) =>
part.toLowerCase() === query.toLowerCase() ? (
<mark key={index}>{part}</mark>
) : (
part
),
)}
</>
);
}
return text;
};
const Note = ({ title }) => {
const searchQuery = useSelector((state) => state.view.searchQuery);
return <p>{ highlightText(title, searchQuery) }</p>
}

감사합니다 ㅠㅠ