0

I am trying to replace all the occurrences of character % and _.

Say var inputStr = '_temp_temp2%temp3';
I can replace it by var replacedStr = inputStr.replace(/_/g, '\\_').replace(/%/g, '\\%');

And this also gives me the same result var replacedStr = inputStr.replace(/\_/g, '\\_').replace(/\%/g, '\\%');

What is the difference between these two? Is there any significance of putting that extra \ in second case? Currently I am getting same output for both the cases, is there any risk of using the first method i.e. without the escape caharacter \? I have tried to understand from MDN, but didn't understand it properly.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Debajit Majumder
  • 824
  • 1
  • 11
  • 22
  • *single slash* works as an escape character only if the resulting string after prepending `\\` also has a special meaning, otherwise it is ignored. – gurvinder372 Apr 19 '17 at 06:41
  • @Wiktor Stribiżew - I have gone through the answers that you have marked as duplicate. But that doesn't give me the answer for this particular case(or I am not understanding). My simple question is what is the difference if I don't escape the special character because I'm getting the same output for both. Is there any risk of using the first approach? – Debajit Majumder Apr 19 '17 at 09:00
  • Never escape characters that do not have to be escaped - this is the only safe approach. `_` is a **word**, not a special char, it should never be escped. `%` is not a special regex operator and thus should never be escaped. – Wiktor Stribiżew Apr 19 '17 at 09:02
  • Thanks. So, does that mean that though it's giving the same result, 2nd approach is not safe! I should not escape `%` and `_` in Javascript and use the first approach. – Debajit Majumder Apr 19 '17 at 09:05

0 Answers0