JSFiddle - React, Tailwind, and code Playground

by CommandLineDesign

JavaScript

var s = '0 - 22 1985--324';


function solution(s){
	var phoneNumber = s.replace(/\D/g,'').split('');
    var result = [];
    for(var i = 1; i <= phoneNumber.length; i++){
    	currentDigit = phoneNumber[i-1];
        if(i % 3 == 0 && i !== phoneNumber.length){
            
        	currentDigit += '-'
        }
        result[i-1] = currentDigit;
    }
    var checkSegmentSize = result.join('');
    console.log(checkSegmentSize);
    var lastDash = checkSegmentSize.lastIndexOf('-');
    console.log(lastDash);
    console.log(checkSegmentSize.length);
    if(lastDash == checkSegmentSize.length+2){
        console.log('true');
    	//One trailing element
        result.splice(lastDash,1);
        result.splice(lastDash-1, 0, '-');
    }
    //Now check to make sure the last group has more than one digit?   
    return result.join('');
}

console.log(solution(s));