Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 847
at. Avatar asked Dec 12 '16 19:12

at.


People also ask

How will you replace all occurrences of a string in JavaScript?

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')

How do you replace all occurrences of a character in a string in JavaScript?

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.

How do you replace a character in a string in JavaScript without using replace method?

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.

What is replace (/ g in JavaScript?

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.


1 Answers

You can just split and join it again string.split('.').join('%20')

like image 132
Jeremy Jackson Avatar answered Oct 10 '22 16:10

Jeremy Jackson