1

I'm looking for a function that does replaceAll with any start and endcharacter.

I know I can use the regex notation:

string=string.replace(/a/g,"b");

However, because the searched char is in a regex, I sometimes need to escape that character and sometimes not, which is annoying if I want to do this for a full list of chars

convertEncoding= function(string) {
   var charMap= {'"':""",'&':"&",...}

   for (startChar in charMap) {
      endChar=charMap[startChar];
      string= string.replaceAll(startChar,endChar);
   }
}

Is they a good way to write that function replaceAll, without doing a for loop and using String.replace() (eg the naive way) ?

edi9999
  • 16,352
  • 11
  • 70
  • 121

1 Answers1

2

you can use escape the RegExp special characters in the strings such as described here https://stackoverflow.com/a/6969486/519995:

and then you can use the regexp global replace

function escapeRegExp(str) {
   return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

for (startChar in charMap) {
   endChar=charMap[startChar];
   result = string.replace(RegExp(escapeRegExp(startChar), 'g'), endChar);
}
Community
  • 1
  • 1
Iftah
  • 8,798
  • 2
  • 28
  • 41
  • Ok, actually I think this would be kind of slow, I'd rather write the regexes myself. – edi9999 May 22 '14 at 11:14
  • @edi9999 1) I doubt this would be slow - at least nothing a human would notice unless you convert millions of encodings 2) you can escape the strings only once on startup and not each time you convertEncoding so its only a tiny bit slower on startup 3) doing it yourself will take more time to develop (write, test, debug, maintain, read) – Iftah May 22 '14 at 12:27
  • Ok, I've tested it and that's true – edi9999 May 22 '14 at 13:41