Javascript Masking se a entrada corresponde ao padrão

document.getElementById("phone").addEventListener("keyup", function(){
    // restart the match
    this.value = this.value.replace(/\s/g, "");
    // Assess the amount needed
    var v = this.value.match(/(\d)(\d{1,3})?(\d{1,2})?(\d+)?/);
    if(v){
      // Save the desired value depending on its existence
      v =  (v[1]?v[1]+(v[2]?" "+v[2]+(v[3]?" "+v[3]+(v[4]?" "+v[4]:""):""):""):"");
      // and yea!
      this.value = v;
    }
});
Crowded Copperhead