Highlight text in multiple <div> elements
Before you start - checklist
- [x] I have read documentation in README
- [x] I have checked sample and test suites to see real life basic implementation
- [x] I have checked if this question is not already asked
What are you trying to achieve? Please describe. Hello! Thank you very much for this awesome react lib! I am currently using it with he annotation layer, and so far it works nicely! It finds the word pattern in the text and highlights it. But i would like to highlight e.g. multiple lines (where sometimes, these elements could be splited in different div elements in the text-layer).
Describe solutions you've tried
my current solution is the one that you have already mentioned on git hub! but it takes each elements of the layer and compares the text:
const highlightPattern = (text, pattern) => {
const splitText = text.split(pattern);
if (splitText.length <= 1) {
return text;
}
const matches = text.match(pattern);
console.log(matches)
return splitText.reduce((arr, element, index) => (matches[index] ? [
...arr,
element,
<mark key={uuid()}>
{matches[index]}
</mark>,
] : [...arr, element]), []);
So it will always compare the whole string in an element, correct?
Additional information
Now a visual example to make it more appealing :P
and now once i past the threshold to the "other div".
searchstring: "Congratulations, your computer is equipped with a PDF (Portable Document Format) #reader"

Environment
- Browser (if applicable) [Firefox 59]:
- React-PDF version [e.g. 3.0.5]:
- React version [e.g. 16.3.2]:
- Webpack version (if applicable) [e.g. 4.8.3]:
Thanks in advance!
I'm not sure I totally understand your request -- are you trying to highlight multiple phrases, rather than just one? If so, this small modification to the recipe works for me:
highlightPattern = (text, highlightWords) => {
// This is the only major change -- rather than searching for a string, create a regex to search
// for any strings in a provided array
const regex = new RegExp(highlightWords.join('|'), 'gi')
const splitText = text.split(regex)
if (splitText.length <= 1) {
return text
}
const matches = text.match(regex)
return splitText.reduce(
(arr, element, index) =>
matches[index]
? [...arr, element, <mark>{matches[index]}</mark>]
: [...arr, element],
[]
)
}
"are you trying to highlight multiple phrases, rather than just one? If so, this small modification to the recipe works for me" ==> yes!
are you providing the function an array with "highlightWords" ? Because i'am working with a string
state = {
searchText: ""
}
makeTextRenderer = searchText => textItem => highlightPattern(textItem.str, searchText);
...
<Page
key={uuid()}
onLoadSuccess={this.pageRendered}
pageNumber={this.state.pageNumber}
customTextRenderer={this.makeTextRenderer(this.state.searchText)}
renderAnnotationLayer="true"
renderInteractiveForms="true"
/>```
Yes, highlightWords is an array of strings to highlight. Change your searchText to be an array instead of just a string.
@taherbert Thy first of all for your effort :)
Okay i got it!
i have spitted it into each word, but i still will get other words highlighted, which are in other sentences.
Do you have an idea, how i can cut them out of the equation? eg.g:
PDF:
Highlighted sentence:

Thanks!
You mean that you want to highlight words, but only in that specific sentence and nowhere else? You would probably need to search for the full sentence inside of highlightPattern, and only apply the highlights when you detect that full sentence.
Alright thanks again!
I'm closing this issue to give other issues more visibility. If you still need assistance with this matter, please do not hesitate to reply and I'll reopen.
Happy coding!
any help on how to convert to 'full sentence inside of highlightPattern' ?
Hi @jack85811 Can you please let me know how you solved the initial problem, where search string is spread across multiple div elements ? @wojtekmaj I think its library's limitation, as the text parameter passed in highlightPattern method will not have words from multiple div elements, so we can search for a key phrase spanning across multiple div elements. Is there any way around ?
Hi @nish5uec, i do have to give you as disclaimer that i dont really know anymore, but the way that i grabbed the text its the following:
getSelectionText = () => {
var t = "";
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
let stringarray = escapeRegExp(t.toString()).split("\n")
let array = stringarray.filter((item)=>{
return item !== " " ? item : "";
})
this.setState({searchText: array})
};
Hope it helps, but it is a long time ago since i have used this lib actively!
<Page
className="page"
ref={(ref) => {
pageRefs[p] = ref
}}
scale={scale}
onRenderSuccess={() => {
// eslint-disable-next-line @typescript-eslint/naming-convention
function find_csa(arr: string | any[], subarr: string | any[], from_index: number) {
// eslint-disable-next-line no-bitwise
let i = from_index >>> 0
const sl = subarr.length
const l = arr.length + 1 - sl
// eslint-disable-next-line no-labels,no-restricted-syntax,no-plusplus
loop: for (; i < l; i++) {
// eslint-disable-next-line no-plusplus
for (let j = 0; j < sl; j++)
if (arr[i + j] !== subarr[j])
// eslint-disable-next-line no-continue,no-labels
continue loop
return i
}
return -1
}
// @ts-ignore
// eslint-disable-next-line react/no-find-dom-node
const textSpan = ReactDOM.findDOMNode(
pageRefs[p]
// @ts-ignore
)!!.getElementsByClassName(
'react-pdf__Page__textContent'
)[0].children
textSpans.push({ page: p, span: textSpan })
loadedPage += 1
if (pageNumber !== 0 && loadedPage === pageNumber) {
console.log(textSpans)
const text = []
const pos = []
// eslint-disable-next-line no-restricted-syntax
for (const pp of textSpans) {
console.log(pp)
// eslint-disable-next-line no-restricted-syntax,guard-for-in
for (let i = 0; i < pp.span.length; i += 1) {
const preLen = text.length
text.push(...pp.span[i].innerText.split(/\s+/)) // second console output
pos.push({
start: preLen,
end: text.length,
span: pp.span[i],
})
}
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const to_search = 'Aggregation of Holistically-Nested Convolutional Neural Networks for Automated Pancreas Localization and'.split(
/\s+/
)
console.log(text)
console.log(pos)
const from = find_csa(text,to_search,0)
const to=from + to_search.length
const toHightlight = []
// eslint-disable-next-line no-restricted-syntax
for(const ss of pos){
if(ss.start > from && ss.end < to){
toHightlight.push(ss.span)
}
if(ss.start < from && ss.end > from){
toHightlight.push(ss.span)
}
if(ss.start < to && ss.end > to){
toHightlight.push(ss.span)
}
}
console.log(toHightlight)
// eslint-disable-next-line no-restricted-syntax
for(const spa of toHightlight){
spa.innerHTML = `<mark>${spa.innerHTML}</mark>`
}
}
}}
pageNumber={p}
/>
here is a makeshift solution,works by calling ReactDOM and directly control the TextLayer,very ugly,yet effective