Tom
Tom

Reputation: 5121

Why can String.raw handle double backslashes but regular escaping can't?

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:

Upvotes: 0

Views: 831

Answers (1)

deceze
deceze

Reputation: 522442

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.

Upvotes: 1

Related Questions