Adding Firebase data, dots and forward slashes

后端 未结 9 2071
长情又很酷
长情又很酷 2020-12-01 12:32

I try to use firebase db, I found very important restrictions, which are not described in firebase help or FAQ.

First problem is that symbol: dot \'.\' prohibited in

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 13:03

    I faced the same problem myself, and I have created firebase-encode for this purpose.

    Unlike the chosen answer, firebase-encode encodes only unsafe characters (./[]#$) and % (necessary due to how encoding/decoding works). It leaves other special characters that are safe to be used as firebase key while encodeURIComponent will encode them.

    Here's the source code for details:

    // http://stackoverflow.com/a/6969486/692528
    const escapeRegExp = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    
    
    const chars = '.$[]#/%'.split('');
    const charCodes = chars.map((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
    
    const charToCode = {};
    const codeToChar = {};
    chars.forEach((c, i) => {
      charToCode[c] = charCodes[i];
      codeToChar[charCodes[i]] = c;
    });
    
    const charsRegex = new RegExp(`[${escapeRegExp(chars.join(''))}]`, 'g');
    const charCodesRegex = new RegExp(charCodes.join('|'), 'g');
    
    const encode = (str) => str.replace(charsRegex, (match) => charToCode[match]);
    const decode = (str) => str.replace(charCodesRegex, (match) => codeToChar[match]);
    

提交回复
热议问题