How to format an input as the user types?

I was looking for some more efficient methods on how to format an input as the user types in both a key event and the standard input event, but I found many ideas confusing, using loops and other unnecessary actions.

Well, that’s my view, I’m publishing the question and I’ll be solving it with my answer, if anyone has a good idea you can also post it. Imagine I decide to format this 123456789 to this 123.456.78-9 or (123) 456 789.