UNPKG

@wordpress/components

Version:
45 lines (40 loc) 1.15 kB
import { createElement, Fragment } from "@wordpress/element"; /** * WordPress dependencies */ import { createInterpolateElement } from '@wordpress/element'; /** * Internal dependencies */ import { escapeRegExp } from '../utils/strings'; /** * 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" * /> * ); * ``` */ export const TextHighlight = props => { const { text = '', highlight = '' } = props; const trimmedHighlightText = highlight.trim(); if (!trimmedHighlightText) { return createElement(Fragment, null, text); } const regex = new RegExp(`(${escapeRegExp(trimmedHighlightText)})`, 'gi'); return createInterpolateElement(text.replace(regex, '<mark>$&</mark>'), { mark: createElement("mark", null) }); }; export default TextHighlight; //# sourceMappingURL=index.js.map