1

Hi I am using ionic to load article that is the local HTML string.

 <ion-content padding>
  <p  [innerHTML]="url"></p>
</ion-content>

url is the local html string. Now what i want to do is add search bar and search within that html string and higlight and scroll to that text.

Any idea how can i start. I had added search bar

SShah
  • 243
  • 2
  • 17

1 Answers1

1

You can use a pipe to apply the text you've searched, it will be something like this

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'highlight'})

export class HighlightPipe implements PipeTransform {
    transform(text: string, search): string {
        try {
            if (text && search ) {
                text = text.toString(); // sometimes comes in as number
                search = search.trim();
                if (search.length > 0) {
                    let pattern = search.trim().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
                    pattern = pattern.split(' ').filter((t) => {
                        return t.length > 0;
                    }).join('|');
                    let regex = new RegExp(pattern, 'gi');

                    text = text.replace(regex, (match) => `<span class="highlight">${match}</span>`);
                }
            }
        }
        catch (exception) {
            console.error('error in highlight:', exception);
        }
        return text;
    }
}

You can change .scss if you want:

.highlight {
background-color:#FFFF00;
}

So, to use in a template, it would be something like: {{myText | highlight:‘word’}}.

Brian Ducca
  • 189
  • 7