I want to replace periods in a string with %20 for Firebase key purposes. I can do 1 period at a time with:
string.replace('.', '%20')
I can even do all of them with a /g
regex flag:
string.replace(/\./g, '%20')
But Firebase rules gives me an error:
Error saving rules - Line 5: regular expressions do not support flags other than i
So I need an expression that replaces all periods without using /g
. I could just chain .replace('.', '%20')
a bunch of times:
string.replace('.', '%20').replace('.', '%20').replace('.', '%20').replace('.', '%20')
But I'm hoping there's a better way.
UPDATE: I had tried string.split('.').join('%20')
, but Firebase throws the error:
Type error: Function call on target that is not a function.
I guess they took out the split
function in their JSON rules parser.
UPDATE 2: I also tried (function() {var s = auth.token.email; while (s.indexOf('.') != -1) { s = s.replace('.', '%20') } return s})()
. Firebase complained that function definitions are not allowed in their database rules.
UPDATE 3: Thanks to Firebase's wonderful support, I found out that the string.replace
function in their database rules has been replaced with a version that replaces all occurrences of the substring, not just a single occurrence. So actually string.replace('.', %2E')
works perfectly!
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.
You can just split and join it again string.split('.').join('%20')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With