无法返回子字符串值角度打字稿

时间:2020-07-28 15:26:03

标签: javascript angular typescript

html

<p>
    <input type="text" maxlength="40" (input)="recipientReference = deleteSpacing(recipientReference)" [(ngModel)]="recipientReference" style="width: 30vw; padding: 5px;border: 1px solid;border-radius: 5px" />

</p>

ts

deleteSpacing(object){
        if(object == this.recipientReference){
          if(object.replace(/\s/g, "").length > 11){
            let phone = this.recipientReference.substring(0, 2);
            if (phone == "+6") {
              
              return object.replace(/\s/g, "").substring(2, 13);
            }
            return object.replace(/\s/g, "").substring(0, 11);
          }
          else {
            return object.replace(/\s/g, "");
          }
        } else {
          return object.replace(/\s/g, "");
        }
    return object;
  }

返回object.replace(/ \ s / g,“”).substring(0,11); 将不返回子字符串,而是返回整个字符串。为此, 返回object.replace(/ \ s / g,“”).substring(0,10); 将返回子字符串。

如何获取11个字符的子字符串?

1 个答案:

答案 0 :(得分:0)

首先,您可以使用regEx删除空格,然后使用substring()获取子集

 var str = "How can i get the substring with 11 characters";
  var res = str.replace(/\s/g, '').substring(0, 11);