如何在JavaScript中进行字符串插值?
考虑以下代码:如何在JavaScript中进行字符串插值?,javascript,string,string-interpolation,Javascript,String,String Interpolation,考虑以下代码: var age = 3; console.log("I'm " + age + " years old!"); 除了字符串串联之外,还有其他方法可以将变量的值插入字符串吗?如果您真的想用大锤敲开螺母,您可以使用: var template = new Template("I'm #{age} years old!"); alert(template.evaluate({age: 21})); 如果你真的想用大锤敲开坚果,你可以使用: var template = new T
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串串联之外,还有其他方法可以将变量的值插入字符串吗?如果您真的想用大锤敲开螺母,您可以使用:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
如果你真的想用大锤敲开坚果,你可以使用:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
试试library(一个完整的开源JavaScript sprintf实现)。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
获取参数数组并返回格式化字符串。Try library(一个完整的开源JavaScript sprintf实现)。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
获取参数数组并返回格式化字符串。Douglas Crockford的函数包括string.prototype.replacement
函数。它简短、熟悉且易于使用:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
如果您不想更改字符串的原型,您可以始终将其调整为独立的,或者将其放置到其他名称空间中,或者其他任何地方。Douglas Crockford的包含一个String.prototype.replacement
函数。它简短、熟悉且易于使用:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
如果您不想更改字符串的原型,您可以始终将其调整为独立的,或者将其放置到其他名称空间中,或者其他任何地方。注意事项:避免使用任何不允许您转义其自身分隔符的模板系统。例如,使用此处提到的
replacant()
方法无法输出以下内容
“由于我的{age}变量,我才3岁。”
简单的插值可能适用于小型自包含脚本,但通常会伴随此设计缺陷,从而限制任何严肃的使用。老实说,我更喜欢DOM模板,例如:
<div> I am <span id="age"></span> years old!</div>
注意:避免使用任何不允许您转义自己的分隔符的模板系统。例如,使用此处提到的
replacant()
方法无法输出以下内容
“由于我的{age}变量,我才3岁。”
简单的插值可能适用于小型自包含脚本,但通常会伴随此设计缺陷,从而限制任何严肃的使用。老实说,我更喜欢DOM模板,例如:
<div> I am <span id="age"></span> years old!</div>
试试看,一个用于字符串插值的轻量级JavaScript模块
你能行
Kiwi.compose("I'm % years old!", [age]);
或
试试看,一个用于字符串插值的轻量级JavaScript模块
你能行
Kiwi.compose("I'm % years old!", [age]);
或
这里有一个解决方案,要求您为对象提供值。如果不提供对象作为参数,它将默认使用全局变量。但是最好还是坚持使用参数,它会更干净
String.prototype.interpolate=函数(props){
返回此。replace(/\{(\w+)\}/g,函数(match,expr){
返回(道具| |窗口)[expr];
});
};
//测试:
//使用参数(建议的方法)
document.getElementById(“resultA”).innerText=“expreation 1:{expreation1}”。插值({expreation1:112});
//使用全局范围
var喷发2=116;
document.getElementById(“resultB”).innerText=“Expreation 2:{Expreation2}”.interpolate()代码>
这里有一个解决方案,要求您为对象提供值。如果不提供对象作为参数,它将默认使用全局变量。但是最好还是坚持使用参数,它会更干净
String.prototype.interpolate=函数(props){
返回此。replace(/\{(\w+)\}/g,函数(match,expr){
返回(道具| |窗口)[expr];
});
};
//测试:
//使用参数(建议的方法)
document.getElementById(“resultA”).innerText=“expreation 1:{expreation1}”。插值({expreation1:112});
//使用全局范围
var喷发2=116;
document.getElementById(“resultB”).innerText=“Expreation 2:{Expreation2}”.interpolate()代码>
tl;博士
如果适用,请使用ECMAScript 2015的模板字符串文本
解释
根据ECMAScript 5规范,没有直接的方法可以做到这一点,但ECMAScript 6已经做到了,这在规范起草过程中也是众所周知的。使用它们如下:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
util.format("Hello my name is %s", "Brent");
> Hello my name is Brent
您可以在{}
中使用任何有效的JavaScript表达式。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
另一件重要的事情是,你不必再担心多行字符串了。你可以简单地把它们写成
> `foo
... bar`
'foo\n bar'
注意:我使用io.jsv2.4.0来评估上面显示的所有模板字符串。您还可以使用最新的Chrome来测试上述示例
注意:ES6规范是,但尚未由所有主要浏览器实现
根据,这将从以下版本开始实施基本支持:Firefox 34、Chrome 41、Internet Explorer 12。如果您是Opera、Safari或Internet Explorer用户,并且现在对此感到好奇,则可以使用它进行游戏,直到每个人都得到支持。tl;博士
如果适用,请使用ECMAScript 2015的模板字符串文本
解释
根据ECMAScript 5规范,没有直接的方法可以做到这一点,但ECMAScript 6已经做到了,这在规范起草过程中也是众所周知的。使用它们如下:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
util.format("Hello my name is %s", "Brent");
> Hello my name is Brent
您可以在{}
中使用任何有效的JavaScript表达式。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
另一件重要的事情是,你不必再担心多行字符串了。你可以简单地把它们写成
> `foo
... bar`
'foo\n bar'
注意:我使用io.jsv2.4.0来评估上面显示的所有模板字符串。您还可以使用最新的Chrome来测试上述示例
注意:ES6规范是,但尚未由所有主要浏览器实现
根据,这将从以下版本开始实施基本支持:Firefox 34、Chrome 41、Internet Explorer 12。如果您是Opera、Safari或Internet Explorer用户,并且现在对此感到好奇,则可以使用它来玩游戏,直到每个人都得到支持。如果您希望在控制台.log
输出中插入,则只需
console.log("Eruption 1: %s", eruption1);
^^
这里,%sconsole.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError
let age = 3;
console.log(`I'm ${age} years old!`);