0

Matching double backslashes in a string requires two escape backslashes. But event that doesn't match in native JavaScript functions as can be seen below:

const str = 'sj\\sf\sd'

str.match(/\\\\/g);                  /*null*/
str.indexOf('\\\\');                 /*-1*/
str.replace(/\\\\/, '')              /*'sj\sfsd'*/   /*<--wrong characters replaced*/

Whereas String.raw works:

const str = String.raw`sj\\sf\sd`

str.match(/\\\\/g);                  /*['\\']*/
str.indexOf('\\\\');                 /*2*/
str.replace(String.raw`\\`, '')      /*'sjsf\sd'*/

Similar questions have been asked about this topic but none explain the reason behind this quirkiness:

Tom
  • 4,776
  • 2
  • 38
  • 50

1 Answers1

1

That’s exactly what String.raw is for: it does not interpret escape sequences. A backslash has a special meaning in a string, so you need to double it to get one actual backslash. With String.raw, (most) special characters lose their special meaning, so two backslashes are actually two backslashes. It’s used precisely when you need a string with many special characters and don’t want to worry about escaping them correctly too much.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks @deceze! My question is rather why correctly escaping double backslashes produces non standard behavior. I mean why does escaping one backslash work as expected but escaping two doesn't? – Tom Apr 21 '19 at 09:42
  • You’ll have to elaborate, I don’t understand. You’re interpreting something differently from me here. – deceze Apr 21 '19 at 09:53
  • 1
    I have understood my mistake. 'sj\\sf\sd' is evaluated as 'sj\sfsd' and hence the behavior. Thanks again – Tom Apr 21 '19 at 10:08