Convert given string to a valid mobile number | Function to print the valid and formatted phone number ; Length of given String ; Store digits in temp ; Iterate given M ; If any digit , append it to temp ; Find new length of String ; If length is not equal to 10 ; Store final result ; Make groups of 3 digits and enclose them within ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; Print final result ; Given String ; Function Call
function Validate ( M ) { let len = M . length ; let temp = " " ; for ( let i = 0 ; i < len ; i ++ ) { if ( ! isNaN ( parseInt ( M [ i ] ) ) ) temp += M [ i ] ; } let nwlen = temp . length ; if ( nwlen != 10 ) { document . write ( " " ) ; return ; } let res = " " ; let x = temp . substring ( 0 , 3 ) ; res += " " + x + " " ; x = temp . substring ( 3 , 6 ) ; res += " " + x + " " ; x = temp . substring ( 6 , 9 ) ; res += " " + x + " " ; x = temp . substring ( 9 , 10 ) ; res += " " + x + " " ; document . write ( res + " " ) ; } let M = " " ; Validate ( M ) ;