How to replace all periods in a string with JavaScript without / g?

I want to replace periods in a row 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 the /g flag:

 string.replace(/\./g, '%20') 

But Firebase rules give 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 .replace('.', '%20') bunch of times:

 string.replace('.', '%20').replace('.', '%20').replace('.', '%20').replace('.', '%20') 

But I hope that there will be a better way.

UPDATE : I tried string.split('.').join('%20') , but Firebase throws an error:

Type error: calling a function for a target that is not a function.

I assume they pulled the split function in their JSON rule 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 its database rules.

UPDATE 3 . Thanks to the wonderful support of Firebase, I found out that the string.replace function in my database rules has been replaced by a version that replaces the appearance of an all substring, not just one occurrence. So actually string.replace('.', %2E') works just fine!

+5
source share
2 answers

You can simply split and rejoin it string.split('.').join('%20')

+9
source

Since Firebase complains when you are also trying to clearly respond better to split, then join in, try this ...

 var s = "this.is.a.string.value"; while (s.indexOf(".") != -1) { s = s.replace(".", "%20"); } console.log(s); 
0
source

Source: https://habr.com/ru/post/1261155/


All Articles