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个字符的子字符串?
答案 0 :(得分:0)
首先,您可以使用regEx删除空格,然后使用substring()获取子集
var str = "How can i get the substring with 11 characters";
var res = str.replace(/\s/g, '').substring(0, 11);