How do I setSelection after a text search?


April 2019


7 time


I am attempting to add a search feature to Quill and want to highlight the text that it finds. I am having trouble getting the range index for the text it finds, and it is likely that I am not using the correct approach.

So far, I get the text using getContents() and can find matches by iterating through the lines. However, I have not been able to find the correct index position for setSelection(). A second issue is that I want the window to scroll to where the selection is found, and it is not scrolling into view.

myKeyPhrases = ['obvious', 'orange', 'apple'];

var myDelta = editor.getContents();
myDelta.eachLine((line, attributes, i) => {

    mytext = line.filter((op) => typeof op.insert === 'string').map((op) => op.insert).join('');
    mytext = mytext.toLowerCase();

    ndx = isKeyPhraseFound(mytext, myKeyPhrases); 
    if (ndx >= 0){
        // The code finds the matches OK to here.
        // The next 4 lines don't get the correct range and scroll.
        index = i;
        editor.setSelection(index, 1, Quill.sources.USER); 
        return index;

My desired results would be that a found text match would be selected and that the window would be scrolled so that the selection is displayed. The actual results are that the wrong text is selected and the window is not scrolled to view the selection.

0 answers