TOTP secret keys must be in Base 32. The only valid characters are letters (A-Z, any case) and digits from 2-7. You can use a regular expression to strip invalid characters: Replace all instances of /[^a-zA-Z2-7]/ with an empty string.
/[^a-zA-Z2-7]/