1.0.5 • Published 2 years ago

highlight-multiple-words v1.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Highlight-multiple-words

API

The Highlight-multiple-words provide a function as findAll. This function searches a string of text for a set of search terms and returns an array of "ChunkArg" that describe the matches found.

Note - If searchWords has duplicate child or empty string it will automatically discard For Example 1. "apple","Dummy","apple" = "apple","Dummy" 2. " " =

It returns Array<ChunkArg>. It consists start(number), end(number) and isHighlight(boolean). isHighlight is true when a chunk is a match else false. For Example:

import { findAll } from "highlight-multiple-words";
import type { ChunkArg, FindChunksArg } from "highlight-multiple-words";

export default function App() {
  const textToHighlight = "Lorem Ipsum is simply dummy text.";
  const searchWords = ["Lorem Ipsum", "dummy"];
  
  //const textToHighlight = "लोरेम इप्सम प्रिंटिंग और टाइपसेटिंग उद्योग का केवल डमी टेक्स्ट है।";
  //const searchWords = ["लोरेम इप्सम", "डमी"];
   
  //const textToHighlight = "लोरेम इप्सम प्रिंटिंग और टाइपसेटिंग उद्योग का केवल डमी टेक्स्ट है। Lorem Ipsum is simply dummy text.";
  //const searchWords = ["लोरेम इप्सम", "डमी", "Lorem Ipsum", "dummy"];
  
  const chunks: ChunkArg[] = findAll({
    searchWords,
    textToHighlight
  });

  return (
    <div className="App">
      {chunks.map((chunk, index) => {
          const text: string = textToHighlight.substr(
            chunk.start,
            chunk.end - chunk.start
          );
          return chunk.isHighlight ? (
              <span key={text} style={{ color: "red" /* highlight style */}}>
                {text}
              </span>
            ) : (
              <span key={text}>{text}</span>
            );
        })}
      </div>
  );
}

Run this example on Code Sandbox.

findAll

The findAll function accepts several parameters, although only the searchWords array and textToHighlight string are required.

ParameterRequired?TypeDefault ValueDescription
autoEscapebooleanEscape special regular expression characters
caseSensitivebooleanfalseSearch should be case sensitive
findChunksFunctionCustom find function (advanced)
sanitizeFunctionCustom sanitize function (advanced)
searchWordstruestring[]Array of words(string) to search for
textToHighlighttruestringText to search and highlight

findAll Response

The findAll return Array<ChunkArg>

Keytype
startnumber
endnumber
isHighlightboolean