正则表达式在带有反应形式的Angular 2+管道中失败

时间:2018-06-29 13:55:55

标签: regex angular angular-reactive-forms

我有以下设置:

模板:

<form [formGroup]="myForm">
  <input formControlName="amount" placeholder="Amount">
</form>

组件:

import { Component, OnInit, HostListener } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UdpCurrencyMaskPipe } from '../../../_helpers/udp-currency- 
mask.pipe';

export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(
    private builder: FormBuilder,
    private currencyMask: UdpCurrencyMaskPipe,
  ) {
    this.myForm = builder.group({
      amount: ['', Validators.required]
    });

    this.myForm.valueChanges.subscribe(val => {
      if (typeof val.amount === 'string') {
        const maskedVal = this.currencyMask.transform(val.amount);
        if (val.amount !== maskedVal) {
          this.myForm.patchValue({amount: maskedVal});
        }
      }
    });
  }    
}

管道:

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

@Pipe({
    name: 'udpCurrencyMask'
})
export class UdpCurrencyMaskPipe implements PipeTransform {
    amount: any;

    transform(value: any, args?: any): any {

        let amount = String(value);

        const beforePoint = amount.split('.')[0];
        let integers = '';
        if (typeof beforePoint !== 'undefined') {
            integers = beforePoint.replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, 
'$&,');
        }
        const afterPoint = amount.split('.')[1];
        let decimals = '';
        if (typeof afterPoint !== 'undefined') {
        decimals = afterPoint.replace(/\D+/g, '');
        }
        if (decimals.length > 2) {
            decimals = decimals.slice(0, 2);
        }
        amount = integers;
        if (typeof afterPoint === 'string') {
            amount += '.';
        }
        if (decimals.length > 0) {
            amount += decimals;
        }

        return amount;
    }
}

,此输入字段的输出行为如下: 输入:1234 输出:1,234(按预期工作) 但是,如果您增加一个数字(例如5),输出将变为 1,2345

我以为正则表达式

/\d{1,3}(?=(\d{3})+(?!\d))/g, '$&,'

将逗号放在适当的位置(例如12,345等123,456等)

我想念什么?谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

似乎您将修改后的字符串(已经包含逗号的字符串)传递给transform函数。

您可以在操作之前删除所有,个字符:

let amount = String(value).replace(/,/g, '');