programing

Angular2에서 텍스트를 잘라내는 방법은 무엇입니까?

starjava 2023. 4. 27. 21:44
반응형

Angular2에서 텍스트를 잘라내는 방법은 무엇입니까?

문자열의 길이를 숫자로 제한할 수 있는 방법이 있습니까?예: 제목 길이를 20으로 제한해야 합니다.{{ data.title }}.

길이를 제한하는 파이프나 필터가 있습니까?

텍스트를 각도로 잘라내는 두 가지 방법.

let str = 'How to truncate text in angular';

해결책

  {{str | slice:0:6}}

출력:

   how to

다음과 같이 조각 문자열 뒤에 텍스트를 추가하려면

   {{ (str.length>6)? (str | slice:0:6)+'...':(str) }}

출력:

 how to...

솔루션(사용자 정의 파이프 생성)

사용자 정의 자르기 파이프를 생성하려는 경우

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'truncate'
})

export class TruncatePipe implements PipeTransform {

transform(value: string, args: any[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

마크업 중

{{ str | truncate:[20] }} // or 
{{ str | truncate:[20, '...'] }} // or

모듈 항목을 추가하는 것을 잊지 마십시오.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

선택적 매개변수를 사용하여 파이프 자르기:

  • limit - 문자열 최대 길이
  • complete Words - 문자 대신 가장 가까운 전체 단어에서 자르기 플래그
  • 생략 부호 - 추가된 후행 접미사

-

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
    if (completeWords) {
      limit = value.substr(0, limit).lastIndexOf(' ');
    }
    return value.length > limit ? value.substr(0, limit) + ellipsis : value;
  }
}

모듈 항목을 추가하는 것을 잊지 마십시오.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

사용.

예 문자열:

public longStr = 'A really long string that needs to be truncated';

마크업:

  <h1>{{longStr | truncate }}</h1> 
  <!-- Outputs: A really long string that... -->

  <h1>{{longStr | truncate : 12 }}</h1> 
  <!-- Outputs: A really lon... -->

  <h1>{{longStr | truncate : 12 : true }}</h1> 
  <!-- Outputs: A really... -->

  <h1>{{longStr | truncate : 12 : false : '***' }}</h1> 
  <!-- Outputs: A really lon*** -->

CSS를 기준으로 텍스트를 자를 수 있습니다.문자 수정이 아닌 너비를 기준으로 텍스트를 잘라내는 데 도움이 됩니다.

CSS

.truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.content {
    width:100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

HTML

<div class="content">
    <span class="truncate">Lorem Ipsum is simply dummied text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
</div>

참고: 이 코드는 두 줄 이상이 아닌 한 줄에 대해 full을 사용합니다.

각도별로 하고 싶다면 케탄의 솔루션이 가장 좋습니다.

다음과 같이:

{{ data.title | slice:0:20 }}

그리고 만약 당신이 줄임말을 원한다면, 여기 해결책이 있습니다.

{{ data.title | slice:0:20 }}...

단어를 기준으로 길이 제한

문자 대신 단어를 기준으로 자르면서 전체 텍스트를 볼 수 있는 옵션을 허용하려면 이 옵션을 사용하십시오.

단어를 기반으로 한 읽기 추가 솔루션을 찾고 사용자 정의 공유Pipe저는 결국 글을 쓰게 되었습니다.

파이프:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {

  transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
    
    if (showAll) {
      return text;
    }

    if ( text.split(" ").length > length ) {
      
      return text.split(" ").splice(0, length).join(" ") + suffix;
    }

    return text;
  }

}

템플릿:

<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>

구성 요소:

export class ExamplePage implements OnInit {

    public showAll: any = false;
    
    triggerReadMore() {
        this.showAll = true;
    }
    
}

모듈 내:

import { ReadMorePipe } from '../_helpers/read-more.pipe';

@NgModule({
  declarations: [ReadMorePipe]
})
export class ExamplePageModule {}

다음은 다음과 같은 방법을 사용하는 대안적 접근법입니다.interface다음을 통해 전달될 옵션 객체의 모양을 설명합니다.pipe표제로

@Pipe({
  name: 'textContentTruncate'
})
export class TextContentTruncatePipe implements PipeTransform {

  transform(textContent: string, options: TextTruncateOptions): string {
    if (textContent.length >= options.sliceEnd) {
      let truncatedText = textContent.slice(options.sliceStart, options.sliceEnd);
      if (options.prepend) { truncatedText = `${options.prepend}${truncatedText}`; }
      if (options.append) { truncatedText = `${truncatedText}${options.append}`; }
      return truncatedText;
    }
    return textContent;
  }

}

interface TextTruncateOptions {
  sliceStart: number;
  sliceEnd: number;
  prepend?: string;
  append?: string;
}

그런 다음 마크업에서:

{{someText | textContentTruncate:{sliceStart: 0, sliceEnd: 50, append: '...'} }}

요청하신 대로 슬라이스 파이프(각형의 코어 파이프)를 사용하면 매우 간단합니다.data.title:

{{ data.title | slice:0:20 }}

From Angular 공통 문서 https://angular.io/api/common/SlicePipe

나는 이 모듈 ng2 자르기를 사용해 왔습니다. 꽤 쉽고, 가져오기 모듈을 사용할 준비가 되었습니다.{{data.dll | 자르기: 20 }}에서.

줄임표를 사용하여 문자열 잘라내기

추가 파이프가 필요 없습니다. 슬라이스를 사용할 수 있습니다.

{{ stringText | slice: 0:25}} {{ stringText.length > 25 ? '...' : ''}}

단어 수만큼 잘라내고 생략 부호를 추가하려면 다음 기능을 사용할 수 있습니다.

truncate(value: string, limit: number = 40, trail: String = '…'): string {
  let result = value || '';

  if (value) {
    const words = value.split(/\s+/);
    if (words.length > Math.abs(limit)) {
      if (limit < 0) {
        limit *= -1;
        result = trail + words.slice(words.length - limit, words.length).join(' ');
      } else {
        result = words.slice(0, limit).join(' ') + trail;
      }
    }
  }

  return result;
}

예:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 5, '…')
> "Bacon ipsum dolor amet sirloin…"

출처: https://github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts

글자 수만큼 잘라내고 단어를 잘라내지 않으려면 다음을 사용합니다.

truncate(value: string, limit = 25, completeWords = true, ellipsis = '…') {
  let lastindex = limit;
  if (completeWords) {
    lastindex = value.substr(0, limit).lastIndexOf(' ');
  }
  return `${value.substr(0, limit)}${ellipsis}`;
}

예:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, true, '…')
> "Bacon ipsum dolor…"

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, false, '…')
> "Bacon ipsum dolor a…"

방금 @Timothy Perez 답변을 시도하고 대사를 추가했습니다.

if (value.length < limit)
   return `${value.substr(0, limit)}`;

로.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {

   if (value.length < limit)
   return `${value.substr(0, limit)}`;

   if (completeWords) {
     limit = value.substr(0, limit).lastIndexOf(' ');
   }
   return `${value.substr(0, limit)}${ellipsis}`;
}
}
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate',
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit: number, trail = '...'): string {
    if (value.length <= limit) {
      return value;
    }

    return value.substring(0, limit - trail.length).replace(/\s+$/, '') + trail;
  }
}
{{ str | truncate: 20 }}
{{ str | truncate: 20:'>>>'] }}

단어로 잘라야 하는 경우:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncateByWords',
})
export class TruncateByWordsPipe implements PipeTransform {
  transform(value: string, limit: number, trail = '...'): string {
    if (value.length <= limit) {
      return value;
    }

    const substr = value.substring(0, limit - trail.length).split(' ');
    const isLastWordFull = value
      .split(' ')
      .find(w => w === substr[substr.length - 1]);

    if (isLastWordFull) {
      return substr.join(' ') + trail;
    }

    return substr.slice(0, -1).join(' ') + trail;
  }
}
{{ str | truncateByWords: 20 }}
{{ str | truncateByWords: 20:'>>>'] }}

(@Nika Kasradze 기준) 끝이나 시작 부분에서 잘라내고 싶은 경우 더 많은 유연성을 위해:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {

  transform(value: string, args: any[]): string {
    const limit = args.length > 0 ? parseInt(args[1], 10) : 20;
    const trail = args.length > 1 ? args[3] : '...';
    return value.length > limit ? (args[2] === 'start' ? trail : '') + value.substr(args[0], limit) + (args[2] === 'end' ? trail : '') : value;
   }
}

어떻게 사용합니까?

{{ myLongText | truncate:[20, myLongText.length-20, 'start', '...'] }}

언급URL : https://stackoverflow.com/questions/44669340/how-to-truncate-text-in-angular2

반응형