jabbascript,
<script>
let reg = /(\+7|\d{3}(?=\d{3})|\d{2}(?=\d{2}))/g;
const func = str => str.replace(reg, `$1 `)
document.write(func('+79219997788') + '<br>')
document.write(func('997788') + '<br>' )
document.write(func('+79219997788') + '<br>')
document.write(func('997788') + '<br>' )
</script>