JavaScript String raw() 是一种静态方法,用于检索模板文字的原始形式。此方法保留文字内容,而不干扰转义序列。
如果第一个参数的值不是 raw 属性,或者新属性为 undefined 或 null,则该方法将引发 'TypeError' 异常。
语法
以下是 JavaScript String raw() 方法的语法 -
String.raw(strings, sub1, sub2, /* …, */ subN)
参数
此方法接受两个名为 'strings' 和 'sub1, sub2, ...subN' 的 URL,如下所述 -
- strings − 模板文本数组对象。
- sub1、sub2,....subN (可选) − 替换的值。
返回值
此方法返回模板文本的原始字符串形式。
示例 1
如果我们只将 string 参数值传递给此方法,它将返回此模板文本的原始字符串形式。
在以下示例中,我们使用 JavaScript String raw() 方法来检索此模板文本 “C:\Apache24\htdocs\javascript\JavaScript String Methods” 的原始字符串形式。
<html>
<head>
<title>JavaScript String raw() Method</title>
</head>
<body>
<script>
const string = "C:\Development\profile\aboutme.html";
document.write("The given string: ", string);
//using the String.raw() method
const filePath = String.raw`C:\Development\profile\aboutme.html`;
document.write("<br>The raw form: ", filePath);
</script>
</body>
</html>
输出
上面的程序返回给定模板文字的原始形式。
The given string: C:Developmentprofileaboutme.html
The raw form: C:\Development\profile\aboutme.html
The raw form: C:\Development\profile\aboutme.html
示例 2
以下是 JavaScript String raw() 方法的另一个示例。我们使用此方法从给定的模板文本 “Hi\n${20+5}!” 中检索原始表单。
<html>
<head>
<title>JavaScript String raw() Method</title>
</head>
<body>
<script>
const string = `Hi\n${20+5}!`;
document.write("The given string: ", string);
//using the String.raw() method
const filePath = String.raw`Hi\n${20+5}!`;
document.write("<br>The raw form: ", filePath);
</script>
</body>
</html>
输出
执行上述程序后,它将返回给定模板文字的原始值。
The given string: Hi 25!
The raw form: Hi\n25!
The raw form: Hi\n25!
示例 3
如果第一个参数 ( string) 的值没有 raw 属性或具有 null 值,它将引发 'TypeError' 异常。
在下面的示例中,我们使用 JavaScript String raw() 方法来检索此模板的原始形式。我们将 null 值作为第一个参数传递给此方法。由于传递的值无效,因此将引发异常。
<html>
<head>
<title>JavaScript String raw() Method</title>
</head>
<body>
<script>
const string = null;
document.write("The given string: ", string);
try {
//using the String.raw() method
const filePath = String.raw(string);
document.write("<br>The raw form: ", filePath);
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
一旦执行了上述程序,它将抛出 'TypeError' 异常。
The given string: null
TypeError: Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object