@wordpress/components
Version:
UI components for WordPress.
30 lines (29 loc) • 1.16 kB
JavaScript
import { createInterpolateElement } from "@wordpress/element";
import { escapeRegExp } from "../utils/strings.mjs";
import { Fragment, jsx } from "react/jsx-runtime";
// packages/components/src/text-highlight/index.tsx
/**
* Highlights occurrences of a given string within another string of text. Wraps
* each match with a `<mark>` tag which provides browser default styling.
*
* ```jsx
* import { TextHighlight } from '@wordpress/components';
*
* const MyTextHighlight = () => (
* <TextHighlight
* text="Why do we like Gutenberg? Because Gutenberg is the best!"
* highlight="Gutenberg"
* />
* );
* ```
*/
const TextHighlight = (props) => {
const { text = "", highlight = "" } = props;
const trimmedHighlightText = highlight.trim();
if (!trimmedHighlightText) return /* @__PURE__ */ jsx(Fragment, { children: text });
const regex = new RegExp(`(${escapeRegExp(trimmedHighlightText)})`, "gi");
return createInterpolateElement(text.replace(regex, "<mark>$&</mark>"), { mark: /* @__PURE__ */ jsx("mark", {}) });
};
TextHighlight.displayName = "TextHighlight";
export { TextHighlight, TextHighlight as default };
//# sourceMappingURL=index.mjs.map