我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。
我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。
当前回答
这里没有看到任何外部库,但Lodash有_.template(),
https://lodash.com/docs/4.17.10#template
如果你已经在使用Lodash库,它值得一试,如果你没有使用Lodash,你可以从npm npm install Lodash中选择方法。模板,这样可以减少开销。
最简单的形式——
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
还有很多配置选项
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
我发现自定义分隔符非常有趣。
其他回答
简单的使用方法:
var util = require('util');
var value = 15;
var s = util.format("The variable value is: %s", value)
在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,不,这在javascript中是不可能的。你将不得不求助于:
var hello = "foo";
var my_string = "I pity the " + hello;
如果你喜欢写CoffeeScript,你可以这样做:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript实际上是javascript,但是语法更好。
要了解CoffeeScript的概述,请查看初学者指南。
我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许你做以下事情
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
这将替换{0}和{1}与数组项,并返回以下字符串
"this is a test string for stringInject"
或者你可以像这样用对象键和值替换占位符:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
"My username is tjcafferkey on Github"
我会使用反撇号' '。
let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
但如果在创建msg1时不知道name1。
例如,如果msg1来自API。
你可以使用:
let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'
const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
return eval(key);
});
console.log(result); // 'Hello Geoffrey'
它将用他的值替换${name2}。