输入内容的slice()

问题描述 投票:1回答:2

我正在Angular中进行一项分配,其中用户必须在输入字段中放入一些内容,当该内容超过27个时,结果应为前27个字符,后跟“ ...”。我正在使用slice()方法,但是即使代码编译并运行它也不会缩短结果。即使是50个字符,我仍然会得到整个输入。

HTML:

<input [(ngModel)]="input1" (keyup)="counter($event)">
<button (click)="shortener()">Make me shorter!</button><br>
{{ notification }}<br>
{{ shorter }}

component.ts:

export class First27Component implements OnInit {

  public input1: string;
  public shorter: string;
  public notification: string;

  constructor() { }

  ngOnInit() {
  }

  counter(event){
  this.input1=event.target.value;
  }

  shortener() {
    let inputLength: number = this.input1.length
    console.log(inputLength)
    if (inputLength >27) {
    this.shorter = this.input1.slice(0,27)+"..."
    } else {
    this.notification = "Jest mniej niż 27 znaków. Szkoda skracać!"
    }
    this.shorter = this.input1
    console.log(this.shorter)
  }

}

这怎么了?也许最好使用RegEx代替?感谢您的任何提示和建议! :)

javascript angular slice
2个回答
1
投票

这不是正确的方法,因为您可能不希望通过修剪丢失数据。最佳做法是存储完整的字符串,并只显示部分字符串,最后以...结尾。

为此,请使用text-overflow: ellipsis;。如果文本溢出固定宽度,将在末尾附加...

这里是完整的指南:https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/


0
投票

制作短字符串后,您将其分配给长字符串,只是对其进行了更改...从此:

 this.shorter= this.input1 

至此:

 this.input1 = this.shorter
© www.soinside.com 2019 - 2024. All rights reserved.