Tuesday, 6 April 2021

Highlight specific words in textarea angular 8

I am trying to select a few words from the textarea and create bootstrap chips.

enter image description here

I am able to create the chips for selected words. I am trying to highlight the selected words with different background colors.

export class SearchComponent implements OnInit {

  constructor() { }

  selectedText = [];
  regexFromMyArray: RegExp;

  // tslint:disable-next-line:typedef
  showSelectedText() {
    let text = '';
    if (window.getSelection) {
      text = window.getSelection().toString();
      if (text) {
        // console.log(this.selectedText.includes(text));
        if (this.selectedText.includes(text) === false)
        {
          this.selectedText.push(text);
          this.regexFromMyArray = new RegExp(this.selectedText.join('|'), 'ig');
          console.log(this.regexFromMyArray);
        }
        }
    }
    // console.log(this.selectedText);
    return this.selectedText;
  }

  // tslint:disable-next-line:typedef
  removeItem(array, item){
    for (const i in array){
      if (array[i] === item){
        array.splice(i, 1);
        break;
      }
    }
  }

  // tslint:disable-next-line:typedef
  deleteChip(el) {
    // el.style.display = 'none';
    document.getElementById(el).style.display = 'none';
    this.removeItem(this.selectedText, el);
  }



  ngOnInit(): void {
  }

}

I am not sure how to highlight the words in the selectedText array. I want to highlight all chip words. Like "Contrary", "Ipsum", "classical", "literature".

Help will be appreciated.



from Highlight specific words in textarea angular 8

No comments:

Post a Comment