← 中文资源

简体中文版本

String.raw 保留模板反斜杠

用 String.raw 标签模板构造 Windows 路径与正则,对比原始反斜杠与普通转义的结果。

阅读英文原文

实现说明

windowsPath、pattern、regex、normal 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 每一步打印都带着自己的标签:path:、contains backslash-n:、pattern:。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件用顶层绑定保存自己的状态:windowsPath、pattern、regex。

核心语句

const joined = String.raw({ raw: ['a', 'b', 'c'] }, '-', '_');
const windowsPath = String.raw`C:\temp\new\file.txt`;
const pattern = String.raw`\d+\.\d+`;

代码示例

// String.raw tagged templates keep backslash escapes literal
const windowsPath = String.raw`C:\temp\new\file.txt`;
console.log('path:', windowsPath);
console.log('contains backslash-n:', windowsPath.includes('\\n'));

const pattern = String.raw`\d+\.\d+`;
console.log('pattern:', pattern);
const regex = new RegExp(pattern);
console.log('matches 3.14:', regex.test('3.14'));

const normal = `C:\temp\new`;
console.log('normal length:', normal.length);
console.log('raw length:', windowsPath.length);
console.log('normal has tab:', normal.includes('\t'));

const joined = String.raw({ raw: ['a', 'b', 'c'] }, '-', '_');
console.log('manual raw call:', joined);
console.log('backslash count:', windowsPath.split('\\').length - 1);