javascript怎么组合字符串(如何在JavaScript中创建原始字符串)(1)

静态 String raw() 方法之所以如此命名,是因为我们可以使用它来获取 JavaScript 中模板文字的原始字符串形式。 这意味着变量替换(例如,${num})会被处理,但像 \n 和 \t 这样的转义序列不会被处理。

例如:

const message = String.raw`\n is for newline and \t is for tab`; console.log(message); // \n is for newline and \t is for tab

我们可以使用原始字符串来避免对文件路径使用双反斜杠并提高可读性。

例如,而不是:

const filePath = 'C:\\Code\\JavaScript\\tests\\index.js'; console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js

我们可以写:

const filePath = String.raw`C:\Code\JavaScript\tests\index.js`; console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js

我们还可以使用它来编写包含反斜杠字符的更清晰的正则表达式。 例如,而不是:

const patternString = 'The (\\w ) is (\\d )'; const pattern = new RegExp(patternString);const message = 'The number is 100'; console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']

我们可以写:

const patternString = String.raw`The (\w ) is (\d )`; const pattern = new RegExp(patternString);const message = 'The number is 100'; console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']

,