Angular2 中 Array<string | RegExp> 中的值如何添加

How Value add in Array<string | RegExp> in Angular2

我在 Angular2 & RegExp

中遇到了一个问题

此包用于 Angular 2 https://github.com/text-mask/text-mask/

文档 https://github.com/text-mask/text-mask/tree/master/angular2#readme

我的问题我可以使用5-6种类型Phone使用的格式

喜欢

以上包使用数组格式

我有这种格式的字符串

'(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/

如何添加数组格式

我可以试试这个代码

代码-1:

var phoneFormat:Array<string | RegExp>;
 var format="'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'";

        var ArrayObj=format.split(',');

       for ( var i = 0; i < ArrayObj.length; i++ ) {
          phoneFormat.push(ArrayObj[i]); 
        }

给出的错误:

Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined

代码 2

 var format=['(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'];
       phoneFormat=format;

Code-2 没有错误但是掩码不起作用

如评论所述,您收到以下错误:

TypeError: Cannot read property 'push' of undefined

因为,你还没有初始化数组

var phoneFormat:Array<string | RegExp>; 只是类型定义。你将不得不做 var phoneFormat:Array<string | RegExp> = [];


现在

"'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'"

是一串格式化字符串。所以当你拆分它时,你只会得到像 "'('".

这样的字符串化字符串

您将不得不解析它。以下示例将有所帮助:

var phoneFormat: Array <string | RegExp> = [];
var format = "'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'";

format.split(',').forEach(function(value){
  if(value.startsWith('\'/')) {
    phoneFormat.push(new RegExp(value.substring(2, value.length-2)));
  }
  else {
    phoneFormat.push(value.substring(1, value.length-1));
  }
});

console.log(phoneFormat)