Here is an example of code done in TypeScript, but you can surely parse it into JavaScript:
const formatPhoneNumber = (phoneNumber: number, format?: string, code?: boolean): string => {
let _format = format === undefined ? '--- --- ---' : format
let x = 1
const newFormat = _format.replace(/-+/g, () => '$' + x++)
let regex = '^'
_format.match(/-+/g)?.forEach((c, k) => {
regex += `(\\d{${c.length}})?`
})
return (code !== undefined && code === true ? '+' : '') + (phoneNumber.toString().concat(_format.split(' ').join(''))).slice(0, _format.split(' ').join('').length).toString().replace(new RegExp(regex, 'g'), newFormat)}
To test it, you can do:
const formatedPhoneNumber = formatPhoneNumber(600000000) // => 600 000 000
const formatedPhoneNumberWithCountryCode = formatPhoneNumber(237600000000, 'xxx xxx xxx xxx', true) // => +237 600 000 000
This example is perfectly modular, so you can do specify your own format (template) to have a different output!
Note: I'm Cameroonian, that's why I used that strange template, Feel free to adapt the template to the needed phone number template