Tom*_*man 464 javascript string string-interpolation
考虑以下代码:
var age = 3;
console.log("I'm " + age + " years old!");
Run Code Online (Sandbox Code Playgroud)
除了字符串连接之外,还有其他方法可以将变量的值插入字符串吗?
Dam*_*ica 447
从ES6开始,您可以使用模板文字:
const age = 3
console.log(`I'm ${age} years old!`)
Run Code Online (Sandbox Code Playgroud)
PS注意使用反引号:``
.
the*_*eye 229
如果适用,请使用ECMAScript 2015的模板字符串文字.
根据ECMAScript 5规范,没有直接的方法可以做到这一点,但ECMAScript 6有模板字符串,在规范的起草过程中也被称为准文字.像这样使用它们:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
Run Code Online (Sandbox Code Playgroud)
您可以在其中使用任何有效的JavaScript表达式{}
.例如:
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
Run Code Online (Sandbox Code Playgroud)
另一件重要的事情是,您不必再担心多行字符串了.你可以简单地把它们写成
> `foo
... bar`
'foo\n bar'
Run Code Online (Sandbox Code Playgroud)
注意:我使用io.js v2.4.0来评估上面显示的所有模板字符串.您还可以使用最新的Chrome来测试上面显示的示例.
注意: ES6规范现已最终确定,但尚未由所有主流浏览器实施.
根据Mozilla开发者网络页面,这将实现从以下版本开始的基本支持:Firefox 34,Chrome 41,Internet Explorer 12.如果您是Opera,Safari或Internet Explorer用户,现在对此感到好奇,这个测试床可以用来玩,直到每个人都得到支持.
Chr*_*sen 186
Douglas Crockford的Remedial JavaScript包含一个String.prototype.supplant
函数.它简短,熟悉且易于使用:
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' }));
Run Code Online (Sandbox Code Playgroud)
如果您不想更改String的原型,您可以始终将其调整为独立的,或将其放入其他名称空间或其他任何名称空间.
gre*_*del 52
注意事项:避免使用任何不允许你逃避自己的分隔符的模板系统.例如,使用supplant()
此处提到的方法无法输出以下内容.
"感谢我的{age}变量,我已经3岁了."
简单插值可能适用于小型自包含脚本,但通常会出现这种设计缺陷,限制任何严重的使用.老实说,我更喜欢DOM模板,例如:
<div> I am <span id="age"></span> years old!</div>
Run Code Online (Sandbox Code Playgroud)
并使用jQuery操作: $('#age').text(3)
或者,如果您只是厌倦了字符串连接,那么总会有替代语法:
var age = 3;
var str = ["I'm only", age, "years old"].join(" ");
Run Code Online (Sandbox Code Playgroud)
Naw*_*Man 23
试试sprintf.例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
Run Code Online (Sandbox Code Playgroud)
shu*_*ter 21
你可以使用Prototype的模板系统,如果你真的想用大锤来破解坚果:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
Run Code Online (Sandbox Code Playgroud)
Jef*_*ave 18
当我不知道如何正确地使用这种模式时,我会在很多语言中使用这种模式,只是想快速得到一个想法:
// JavaScript
var stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
.replace(/{name}/g ,'Indigo Montoya')
.replace(/{action}/g ,'killed')
.replace(/{relation}/g,'father')
;
Run Code Online (Sandbox Code Playgroud)
虽然不是特别有效,但我发现它可读.它始终有效,并且始终可用:
' VBScript
dim template = "Hello, my name is {name}. You {action} my {relation}."
dim stringvalue = template
stringValue = replace(stringvalue, "{name}" ,"Luke Skywalker")
stringValue = replace(stringvalue, "{relation}","Father")
stringValue = replace(stringvalue, "{action}" ,"are")
Run Code Online (Sandbox Code Playgroud)
总是
* COBOL
INSPECT stringvalue REPLACING FIRST '{name}' BY 'Grendel'
INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Mother'
INSPECT stringvalue REPLACING FIRST '{action}' BY 'did unspeakable things to'
Run Code Online (Sandbox Code Playgroud)
小智 17
最简单的是
`my string ${VARIABLE}`
Run Code Online (Sandbox Code Playgroud)
实现此目的效率较低的方法是
function format(str, ...params) {
for(const param of params)
str = str.replace("%", param);
return str;
}
Run Code Online (Sandbox Code Playgroud)
可以与
format("My % string", "interpolation")
Run Code Online (Sandbox Code Playgroud)
Moh*_*rif 11
你可以轻松地使用ES6 template string
并使用任何可用的transila像babel一样转换到ES5.
const age = 3;
console.log(`I'm ${age} years old!`);
Run Code Online (Sandbox Code Playgroud)
http://www.es6fiddle.net/im3c3euc/
小智 10
let age = 3;
console.log(`I'm ${age} years old!`);
Run Code Online (Sandbox Code Playgroud)
您可以使用反引号``和ES6模板字符串
试试kiwi,一个用于字符串插值的轻量级JavaScript模块.
你可以做
Kiwi.compose("I'm % years old!", [age]);
Run Code Online (Sandbox Code Playgroud)
要么
Kiwi.compose("I'm %{age} years old!", {"age" : age});
Run Code Online (Sandbox Code Playgroud)
这是一个需要您为对象提供值的解决方案.如果不提供对象作为参数,则默认使用全局变量.但更好地坚持使用参数,它更清洁.
String.prototype.interpolate = function(props) {
return this.replace(/\{(\w+)\}/g, function(match, expr) {
return (props || window)[expr];
});
};
// Test:
// Using the parameter (advised approach)
document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });
// Using the global scope
var eruption2 = 116;
document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
Run Code Online (Sandbox Code Playgroud)
<div id="resultA"></div><div id="resultB"></div>
Run Code Online (Sandbox Code Playgroud)
小智 5
如果要对console.log
输出进行插值,则只需
console.log("Eruption 1: %s", eruption1);
^^
Run Code Online (Sandbox Code Playgroud)
在这里,%s
就是所谓的“格式说明符”。console.log
具有内置的这种插值支持。
小智 5
找不到我要找的东西,然后找到了 -
如果您使用的是 Node.js,则有一个带有格式函数的内置util
包,其工作方式如下:
util.format("Hello my name is %s", "Brent");
> Hello my name is Brent
Run Code Online (Sandbox Code Playgroud)
巧合的是,现在 Node.js 中也内置了此console.log
功能 -
console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
309530 次 |
最近记录: |