Last active
January 6, 2019 14:41
-
-
Save karol-majewski/420c580df85c35a9baebd764648040ec to your computer and use it in GitHub Desktop.
Finds & highlights given phrases inside a Web document
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type IdentityFunction<T> = (argument: T) => T; | |
| type InnerHTMLTransformer = IdentityFunction<string>; | |
| type RegularExpressionFlags = | |
| | 'i' | |
| | 'g' | |
| | 'ig'; | |
| type Phrase = string | RegExp; | |
| const toRegularExpression = (flags: RegularExpressionFlags) => | |
| (phrase: Phrase): RegExp => | |
| phrase instanceof RegExp | |
| ? phrase | |
| : new RegExp(phrase, flags); | |
| const transformInnerHTML = (transformer: InnerHTMLTransformer) => | |
| (element: Element): void => { | |
| element.innerHTML = transformer(element.innerHTML); | |
| }; | |
| const transform = (phrases: Phrase[], transformer: InnerHTMLTransformer, selector: string = 'body *') => | |
| phrases | |
| .map(toRegularExpression('ig')) | |
| .forEach(expression => | |
| document | |
| .querySelectorAll(selector) | |
| .forEach(transformInnerHTML(innerHTML => innerHTML.replace(expression, transformer))), | |
| ); | |
| const highlight: InnerHTMLTransformer = source => | |
| `<span style="background-color: #fdfbb7">${source}</span>`; | |
| transform( | |
| ['hello', /world/ig], | |
| highlight, | |
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const sanitize = (input: string | null, separator = ','): RegExp[] => | |
| (input === null) | |
| ? [] | |
| : input | |
| .split(separator) | |
| .map(phrase => phrase.trim()) | |
| .map(toRegularExpression('ig')); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage as a bookmarklet: