[英]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:
但是,本机JavaScript函数中不匹配的事件如下所示:
const str = 'sj\\sf\sd'
str.match(/\\\\/g); /*null*/
str.indexOf('\\\\'); /*-1*/
str.replace(/\\\\/, '') /*'sj\sfsd'*/ /*<--wrong characters replaced*/
Whereas String.raw
works: 而
String.raw
工作原理是:
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: 有关此主题的问题类似,但没有人解释这种古怪的原因:
That's exactly what String.raw
is for: it does not interpret escape sequences. 这就是
String.raw
的确切用途:它不解释转义序列。 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. 使用
String.raw
,(大多数)特殊字符失去其特殊含义,因此两个反斜杠实际上是两个反斜杠。 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. 当您需要带有许多特殊字符的字符串并且不想担心过多地正确转义它们时,就可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.