String.raw()是一个模板字符串的标签函数,它的作用类似于 Python 中的字符串前缀r和 C# 中的字符串前缀@,是用来获取一个模板字符串的原始字面量值的。
语法
String.raw(callSite, ...substitutions)String.raw`templateString`
参数
callSite一个模板字符串的“调用点对象”。类似{ raw: ['foo', 'bar', 'baz'] }。...substitutions任意个可选的参数,表示任意个内插表达式对应的值。templateString模板字符串。返回
给定模板字符串的原始字面量值。异常
TypeError如果第一个参数没有传入一个格式良好的调用点对象,则会抛出TypeError异常。描述
不要被上面复杂的参数要求吓到,因为像所有的标签函数一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。
示例
console.log(String.raw`Hi\n${2+3}!`);
// 'Hi\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
console.log(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';
console.log(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:
console.log(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`
console.log(String.raw({
raw: ['foo', 'bar', 'baz']
}, 2 + 3, 'Java' + 'Script')); // 'foo5barJavaScriptbaz'
网友回复
如何用html写出网页滚动视频播放卡片视觉差异效果的代码?
程序员如何低成本搭建代理进行科学上网学习技术?
threejs如何做个三维搭积木的游戏?
three如何实现标记多个起始路过地点位置后选择旅行工具(飞机汽车高铁等),最后三维模拟行驶动画导出mp4?
ai实时驱动的3d数字人可视频聊天的开源技术有吗
swoole+phpfpm如何实现不同域名指向不同目录的多租户模式?
如何用go替换nginx实现请求phpfpm解析运行php脚本?
有没有浏览器离线运行进行各种文档、图片、视频格式转换的开源工具?
如何使用go语言搭建一个web防火墙?
linux如何检测特定网络协议比如http协议中报文是否包含特点关键词并阻止返回给客户?


