searchShowRed.ets 1.46 KB
export interface textItem {
  content: string,
  isRed: boolean
}

export interface titleInitRes  {
  titleMarked: boolean,
  textArr: textItem[]
}

export class SearchShowRed {
  // title: this.contentDTO.title
  static titleInit(title: string) {
    let titleMarked: boolean = false;
    let textArr: textItem[] = [];

    if (title?.includes('<em>') && title?.includes('</em>')) {
      titleMarked = true;

      const html: string = title;
      const pattern = /<[a-z]+[1-6]?\b[^>]*>(.*?)<\/[a-z]+[1-6]?>/g;
      const res: string[] = [];
      let match: RegExpExecArray | null;

      while ((match = pattern.exec(html)) !== null) {
        const content: string = match[1].trim();
        res.push(content);
      }

      SearchShowRed.formatTitle(html, res, 0, textArr);
    }

    const titleInitRes: titleInitRes = {
      titleMarked,
      textArr
    }
    return titleInitRes
  }

  private static formatTitle(textStr: string, matchArr: string[], index: number, textArr: textItem[]) {
    const item: string = matchArr[index];
    const arr = textStr.split(item);
    arr.forEach((str: string, ind: number) => {
      if (ind === 0) {
        textArr.push({
          content: str.replaceAll('<em>', '').replaceAll('</em>', ''),
          isRed: false
        } as textItem)
        textArr.push({
          content: item,
          isRed: true
        })
      } else if (ind === 1) {
        SearchShowRed.formatTitle(str, matchArr, index + 1, textArr)
      }
    })
  }
}