Different ways to insert spaces among variables in an angular component

I have a function below that I want to use to return a slice of characters with a count as shown in the example below.

Example - abcd,test,red,blue,green,yellow

Expected output -

abcd,test,red,blue,g.........................(11)

My code works correctly but instead of using "------" I would like to have spaces between the count numbers.

viewMore(text) {
    if (text.tag_value_constraint && text.tag_value_constraint.values) {
      const enumText = text.tag_value_constraint.values[0];
      const count = 30;
      return enumText.slice(0, count) + (enumText.length > count ? " ("+(enumText.length - enumText.slice(0, count).length)+")" : "");
    }  
  } 

Answer №1

This code snippet is effective

viewMore(text) {
  if (text.tag_value_constraint && text.tag_value_constraint.values) {
    const enumText = text.tag_value_constraint.values[0];
    const count = 30;
    return enumText.slice(0, count) + (enumText.length > count ? " (" + (enumText.length - enumText.slice(0, count).length) + ")" : "");
  }
} 

A more concise alternative using template literals:

viewMore(text) {
  if (text.tag_value_constraint && text.tag_value_constraint.values) {
    const enumText = text.tag_value_constraint.values[0];
    const count = 30;
    const additionalText = (enumText.length > count) ? ` (${(enumText.length - enumText.slice(0, count).length)})` : "";
    return enumText.slice(0, count) + additionalText;
  }
}

Answer №2

 expandView(text) {
      if (text.constraints && text.constraints.values) {
         const selectedText = text.constraints.values[0];
         const limit = 30;
          return selectedText.slice(0, limit) + (selectedText.length > limit ? "      ("+ 
        (selectedText.length - selectedText.slice(0, limit).length)+")" : "");
       `enter code here`}  
   } 

Answer №3

Here is another approach you can try:

    const phrase = 'abcd,test,red,blue,green,yellow';

    function truncatePhrase(phrase) {
      if (phrase) {
        const initialChar = phrase[0];
        const limit = 20;
        return phrase.slice(0, limit) + ' '.repeat(phrase.length - limit) + (phrase.length - limit);
      }  
    }
    
    console.log(truncatePhrase(phrase));

Answer №4

  1. When replacing "------(" with " (" make sure to let me know if you need single or multiple spaces.
  2. There is a question about why the calculation of enumText.slice(0, count).length is necessary when enumText.length > count always results in a length of count.

Take a look at the code snippet below -

viewMore(text) {
if (text.tag_value_constraint && text.tag_value_constraint.values) {
  const enumText = text.tag_value_constraint.values[0];
  const count = 30;
  return enumText.slice(0, count) + (enumText.length > count ? " ("+(enumText.length - count)+")" : "");
}  

}

For handling multiple spaces in interpolation binding {{}}, it won't work - Instead, use the binding in your HTML file as

<p [innerHTML]="enumText"> </p>
using the relevant variable name holding the value.

In the TS file, adjust the code like this -

viewMore(text) {
if (text.tag_value_constraint && text.tag_value_constraint.values) {
  const enumText = text.tag_value_constraint.values[0];
  const count = 30;
  return enumText.slice(0, count) + (enumText.length > count ? " &#160; &#160; &#160; ("+(enumText.length - count)+")" : "");
}  

}

Hoping this solution helps resolve your issue.

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

Iterate through buttons using jQuery and apply an active class when clicked

https://i.sstatic.net/R7Yc4.pngHey there! I'm a beginner when it comes to jQuery. Can someone please guide me on how to loop through buttons, display their contents when clicked, and update the active class each time a button is clicked? I have dupli ...

Adding new elements dynamically to an array in JavaScript while updating values in a ReactJS component

Hello, I am new to React js and facing an issue with a specific scenario. I have an array that is loaded from my database. For this example, let's take a look at the "fields" array: componentDidMount() { axios.get('http://localhost:200 ...

What is the process of creating conditional content projection in Angular?

Looking to implement an optional content projection feature in Angular. Here's the desired structure as an example: <app-root> <app-header></app-header> </app-root> By default, a header is displayed here. <app-root&g ...

How to alter the HTML view in Angular 2 after it has been processed

Here is some Angular 2 code snippet: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: 'Waiting on port ', }) export class AppComponent { } I want to dynamically add the text "3000" ...

A guide on retrieving TypeScript mongoose/typegoose schema

Here is a defined schema for an account class AccountSchema; Below is the model declaration for the account const AccountClass: Model<AccountSchema & Document>; class Account extends AccountClass; Why isn't this functioning as expected? ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

Is there a way to automatically launch a new tab upon arriving from another website?

I currently have a website that displays a table of elements, each with its own set of sub-elements. On another page, I can view the element along with multiple tabs for its corresponding sub-elements. The current setup is depicted as follows: <a clas ...

Exploring ways to add various field values to a single variable in JavaScript

My current objective involves working with a form that contains various input fields structured like this: <input type="text" id="revenue-1" /> <input type="text" id="revenue-2" /> <inpu ...

Ensure that all divs have the same height and padding when resizing

I have 3 divs nested within a parent div. My goal is to dynamically set the height of all the child divs to match the height of the div with the maximum height, even when the screen resizes due to responsiveness. Below is my HTML structure: <div class ...

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

Restrict user input to only numerical values in an input field using jQuery

Is there a way to create an input field that only accepts integer numbers? Even after using regular expressions, the decimal part of the value still shows up. Here's the function I've tried: $(document).on("input", "input", function(e) { t ...

"Endless Cycle Dilemma" Enigma

Upon executing the function below, I encountered the following error: "Error: Possible infinite loop." The issue appears to stem from the use of "0" in the splice method, as changing it to any other number (1-9) eliminates the error. I'm uncertain ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

Having difficulty achieving the desired style with columns and four divs per column as the styling is not coming together as expected

I am currently having trouble displaying these articles vertically (stacked on top of each other) with 4 divs per column in the main section. I am unable to make them the same size or have all of them display the articles stacked one on top of the other. S ...

Comparing Objects in an Array to Eliminate Duplicates and Make Updates in Javascript

I am working with an array of objects that is structured like this: 0: Object ConsolidatedItem_catalogId: "080808" ConsolidatedItem_catalogItem: "undefined" ConsolidatedItem_cost: "0" ConsolidatedItem_description: "Test Catalog Item" ConsolidatedItem_ima ...

Searching for a document in mongoDB using the `findOne` method

I attempted to use a query to find one document in MongoDB and then I tried to log it, but the result was null. const pc = await ProductCategories.findOne({categoriesName : kategor)}) console.log(pc) I expected to retrieve 1 collection from this process { ...

"Subscription in Angular2 allows for conditional return of true or false values

Is there a way to accurately check if a user exists in the database using Firebase and return true if they do? I have a function with the following code: checkIfUserExists(login: string): boolean { this.af.database.list('/users', { query: ...

Protractor: encountering difficulty retrieving all elements with Protractor

Having some trouble retrieving all elements using CSS or a repeater. this.clickRandomEmployee = function(){ employees = elementController.getAllElements('css','#employee-list li'); numberOfEmployees = employees.le ...

What is the reason for the transparency of the angular material modal?

Having an issue with my angular material modal: runProcess(assignmentNumber) { const dialogConfig = new MatDialogConfig(); dialogConfig.autoFocus = true; dialogConfig.data = { assignmentNumber } this.dialog.open(RunPostReleaseProcessCompon ...

Crafting intricate designs using AngularJS

Currently, I am developing a web application utilizing AngularJS + SpringMVC. Due to restrictions in using only pure HTML view pages, server-side frameworks like Tiles are not viable options for me. I suspect that the angularJS ng-view tag may not be robu ...