首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

String.raw

String.raw()是一个模板字符串的标签函数,它的作用类似于 Python 中的字符串前缀r和 C# 中的字符串前缀@,是用来获取一个模板字符串的原始字面量值的。

语法

代码语言:javascript
复制
String.raw(callSite, ...substitutions)

String.raw`templateString`

参数

callSite一个模板字符串的“调用点对象”。类似{ raw: ['foo', 'bar', 'baz'] }...substitutions任意个可选的参数,表示任意个内插表达式对应的值。templateString模板字符串。

返回

给定模板字符串的原始字面量值。

异常

TypeError如果第一个参数没有传入一个格式良好的调用点对象,则会抛出TypeError异常。

描述

不要被上面复杂的参数要求吓到,因为像所有的标签函数一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。

String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。

示例

使用 String.raw()

代码语言:javascript
复制
String.raw`Hi\n${2+3}!`;
// 'Hi\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.

String.raw`Hi\u000A!`;
// 'Hi\u000A!', same here, this time we will get the
//  \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.

let name = 'Bob';
String.raw`Hi\n${name}!`;
// 'Hi\nBob!', substitutions are processed.

// Normally you would not call String.raw() as a function,
// but to simulate `t${0}e${1}s${2}t` you can do:
String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
// Note that 'test', a string, is an array-like object
// The following is equivalent to
// `foo${2 + 3}bar${'Java' + 'Script'}baz`
String.raw({
  raw: ['foo', 'bar', 'baz'] 
}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'String.raw' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'String.raw' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

41

(Yes)

34

No

No

10

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

No

41

(Yes)

34

No

No

10

扫码关注腾讯云开发者

领取腾讯云代金券