如何删除字符串开头的空白但允许中间的空白?

时间:2019-07-19 07:40:38

标签: typescript

如何删除字符串开头的空白,但允许中间的空白?

<mat-form-field fxFlex="25">
  <input matInput placeholder="Name" [(ngModel)]="userCreation.name" name="name" 
        (keypress)="Lastnamecheck($event)" minlength="3" maxlength="30" #name="ngModel" 
        [ngClass]="{ 'is-invalid': f.submitted && name.invalid }" required>
  <mat-error *ngIf="f.submitted && name.invalid" class="invalid-feedback">
    <mat-error *ngIf="name.errors.required"> Name is required</mat-error>
  </mat-error>
</mat-form-field>
Lastnamecheck(event: any) {
    const pattern = /^\S+[a-zA-Z0-9-_\\s]+$/;
    let inputChar = String.fromCharCode(event.charCode);
    if (event.keyCode != 8 && !pattern.test(inputChar)) {
        event.preventDefault();
    }

1 个答案:

答案 0 :(得分:0)

您可以使用String.prototype.replace

const inputStr = '     something in here';
const stripped = inputStr.replace(/^\s*(.*)$/, '$1');

fiddle