Extract the initial sentence or the opening 50 words from a data object in Typescript/JavaScript

Is there a way to extract only the initial line or first 50 words from the data retrieved by the API and store it in a variable?

In the 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>

In the TS File:


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

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

View image description here

I attempted to retrieve the first line from the variable data, using

this.toolTipHtml = data.split('\n')[0];
. However, this approach did not yield the desired result.

Answer №1

Develop a custom function that extracts the initial line or first specified number of words from a given string.

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

  // Extracting the first paragraph
  var index: number = value.indexOf("\n");
  if (index !== -1) {value = value.substring(0, index);}
  
  // Retrieving the first sentence
  index = value.indexOf(".");
  if (index !== -1) {value = value.substring(0, index + 1);};
  
  // Returning the first N words from the remaining content
  return value.split(' ').slice(0, N).join(' ');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Component not appearing in Storybook during rendering

I'm trying to incorporate the MUI Button Component into my storybook and then dynamically change MUI attributes like variant, color, and disabled status directly from the storybook. While I was successful in doing this with a simple plain HTML button, ...

Angular's HostListener triggers twice when the browser's back button is clicked

In my Angular application, I have implemented a @HostListener that triggers when the back button on the browser is clicked. However, I have noticed that the event handler seems to be firing twice - prompting two dialogue boxes when clicking 'Ok'. ...

Unable to utilize class identifiers in TypeScript because of 'incompatible call signatures' restriction

Following the execution of relevant yarn add commands, the following lines were added to the packages.json: "@types/classnames": "^2.2.7", "classnames": "^2.2.6", Subsequently, I incorporated these lines into my typescript files: import * as classnames ...

Is Angular4 preloaded with bootstrap library?

I started a new angular4 project and wrote the code in app.component.html <div class="container"> <div class="row"> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

Guide to configuring global providers in Angular2 version 2.0.0 RC.5

What is the process for setting up global providers when utilizing a new feature called NgModule? In previous instances, I could accomplish this with the following code: bootstrap(AppComponent, [ GlobalServiceAAA, GLOBAL_PROVIDERS_BBB ]); When usin ...

6 Ionic date-time selector

I seem to be encountering some challenges while using Ionic 6 with the new date-time picker. The issue arises when I retrieve a value from the database through a nest service. In the database, the date appears as: “2022-06-30 13:11:54” but upon retriev ...

Managing a scenario with a union type where the value can be retrieved from one of two different functions

There are two similar methods that I want to refactor to eliminate redundant code. The first function returns a single element, while the second function returns multiple elements: //returns a single element const getByDataTest = ( container: HTMLElement ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

Dynamically hide columns in Angular Material Table when screen is resized and move them to a detail row

Is there a way to replicate the functionality of Datatable Jquery in Angular Material Table? I want the exceeded columns to be hidden and go to a detail row when the screen is zoomed out. Here is an example of what I am trying to achieve with Datatable jq ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

Experimenting with a module reliant on two distinct services

I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined. Although I ...

Encountering issues with data binding functionality within the stepper component

Within my web application, I have implemented 2 input fields known as Course name (utilizing an Autocomplete component) and Price (utilizing an input component). Previously, upon selecting a specific Course name, the corresponding Price would be displayed ...

Unable to implement a function from a controller class

I'm currently attempting to organize my Express.js code, but I've hit a snag when trying to utilize a class method from the controller. Here's an example of what my code looks like: product.service.ts export class ProductService { constr ...

Angular NodeJS API failing to retrieve search data

I have implemented a search feature using Angular and Node.js. After testing it with Postman, everything seemed to be working fine. However, when I tried connecting it to the front-end Angular application, I encountered an error. Failed to load resource: t ...

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

What steps should I take to enable users of my library to customize component templates as needed?

I created a customized component to enhance the appearance of bootstrap form controls, intended for use in various projects. I am considering transforming this into a library (a separate npm package with its own @NgModule), but some projects may wish to mo ...

What is the correct method for retrieving a specific child element in React?

In my React project, I have created a component that consists of various subcomponents: import React, { FunctionComponent } from 'react'; import { FormControl, FormGroup, FormGroupProps, FormLabel, FormText, FormTextProps } from 'react-boots ...