I have Face one problem in Angular2 & RegExp
This Package Used in Angular 2 https://github.com/text-mask/text-mask/
Documentation https://github.com/text-mask/text-mask/tree/master/angular2#readme
My Problem I can used 5-6 type Phone Format used
Like
(XXX) XXX XXXX
(XXX) XXX-XXXX
XXX-XXX-XXXX
Above Package used Array Format
I have String this format
'(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/
How I can add in Array Format
I can try this code
Code-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 Given:
Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
Code-2
var format=['(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'];
phoneFormat=format;
Code-2 No Error But masking not working
As commented, you are getting following error:
TypeError: Cannot read property 'push' of undefined
because, you have not initialized the array.
var phoneFormat:Array<string | RegExp>;
is just type definition. You will have to do var phoneFormat:Array<string | RegExp> = [];
Now
"'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'"
is a string of formatted string. So when you split it, you will only get stringified string like "'('"
.
You will have to parse it. Following sample will help:
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)