var a = "123 45 6775 8" a = a.replace(/\s+/g, "").match(/(\d{1,3})(?=((\d{3})*([^\d]|$)))/g).join(" ") alert(a)