get/cut the first line or the first 50 words in a typescript/Js object of data

get/cut the first line or the first 50 words in a typescript/Js object of data

Problem Description:

I need to send only the first line or first 50 words in a variable in the data fetched by the API.

HTML File;

                <td *ngIf="customizedColumns?.details_of_non_conformity?.value">
                                    <span [ngClass]="{'closeLine': rpt.isDeleted == 1}">
                                    <span [tooltip]="popTemplateToolTip"
                                          triggers="mouseenter:mouseleave"
                                          (mouseenter)="mouseEnterToolTip(rpt.detailsOfNonConformity)"
                                          (mouseleave)="mouseLeaveToolTip()"
                                          *ngIf="rpt.detailsOfNonConformity">
                                         <span>{{helperService.removeUnwantedHTMLWithTags(rpt?.detailsOfNonConformity) | truncate:30}}</span>
                                    </span>
                                  </span>
                </td>

TS File:

  mouseEnterToolTip(data) {
    this.toolTipHtml = data.split('.')[0];
    this.toolTipHtml = this.helperService.removeUnwantedHTMLWithTags(this.toolTipHtml);
  }

  mouseLeaveToolTip() {
    this.toolTipHtml = "";
  }

enter image description here

I tried to get the first line in data from variable, this.toolTipHtml = data.split('n')[0]; I also used this but it didn’t work.

Solution – 1

Create a function that returns the first line or first N words from a string.

getFirstSentenceOrFirstNWordsFromValue(N: number, value: string): string{
  if(!value || !N) return '';

  // Get first paragraph
  var index: number = value.indexOf("n");
  if (index !== -1) {value = value.substring(0, index);}
  
  // Get first sentence
  index = value.indexOf(".");
  if (index !== -1) {value = value.substring(0, index + 1);};
  
  // Return first N words of remaining value
  return value.split(' ').slice(0, N).join(' ');
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject