Good way to replace invalid characters in firebase keys?

firebase

Solution

In the email address, replace the dot `.` with a comma `,`. This pattern is best practice.

The comma `,` is not an allowable character in email addresses but it is allowable in a Firebase key. Symmetrically, the dot `.` is an allowable character in email addresses but it is not allowable in a Firebase key. So direct substitution will solve your problem. You can index email addresses without looping.

You also have another issue.

const cleanEmail = email.replace('.',','); // only replaces first dot

will only replace the first dot `.` But email addresses can have multiple dots. To replace all the dots, use a regular expression.

const cleanEmail = email.replace(/\./g, ','); // replaces all dots

Or alternatively, you could also use the `split()` - `join()` pattern to replace all dots.

const cleanEmail = email.split('.').join(','); // also replaces all dots

Problem

My use case is saving a user's info. When I try to save data to Firebase using the user's email address as a key, Firebase throws the following error: Error: Invalid key e@e.ee (cannot contain `.$[]#`) So, apparently, I cannot index user info by their email. What is the best practice to replace the `.`? I've had success changing the `.` to a `-` but that won't cut it since some email's have `-`s in the address. Currently, I'm using ``` var cleanEmail = email.replace('.','`'); ``` but there are likely going to be conflicts down the line with this.

Original source