我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道JavaScript中是否也可以这样做。在不使用串联的情况下在字符串中使用变量 - 它看起来更简洁,更优雅。
答案 0 :(得分:498)
从Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge开始,您可以使用名为Template Literals的ES2015 / ES6功能并使用以下语法:
`String text ${expression}`
模板文字由反向标记(``)(严重重音)括起来,而不是双引号或单引号。
示例:
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
这有多整洁?
加成:
它还允许javascript中的多行字符串而不进行转义,这对于模板非常有用:
return `
<div class="${foo}">
...
</div>
`;
由于旧浏览器(Internet Explorer和Safari&lt; = 8)不支持此语法,您可能希望使用Babel将代码转换为ES5,以确保它可以在任何地方运行。
旁注:
从IE8 +开始,您可以在console.log
:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
答案 1 :(得分:160)
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge,nope,这在javascript中无法实现。你不得不诉诸:
var hello = "foo";
var my_string = "I pity the " + hello;
答案 2 :(得分:40)
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge,没有。虽然你可以尝试sprintf for JavaScript到达那里:
var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
答案 3 :(得分:27)
你可以做到这一点,但它不是特别的
'I pity the $fool'.replace('$fool', 'fool')
如果你真的需要
,你可以轻松编写一个能够智能地执行此操作的函数答案 4 :(得分:9)
如果您想编写CoffeeScript,您可以这样做:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript实际上是javascript,但语法要好得多。
有关CoffeeScript的概述,请查看此beginner's guide。
答案 5 :(得分:9)
您可以使用此javascript函数来执行此类模板操作。无需包含整个库。
"I would like to receive email updates from this store FOO BAR BAZ."
输出:{{1}}
使用函数作为String.replace()函数的参数是ECMAScript v3规范的一部分。有关详细信息,请参阅custom authentication object。
答案 6 :(得分:9)
完整答案,随时可以使用:
var Strings = {
create : (function() {
var regexp = /{([^{]+)}/g;
return function(str, o) {
return str.replace(regexp, function(ignore, key){
return (key = o[key]) == null ? '' : key;
});
}
})()
};
呼叫
Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
将其附加到String.prototype:
String.prototype.create = function(o) {
return Strings.create(this, o);
}
然后用作:
"My firstname is ${first}".create({first:'Neo'});
答案 7 :(得分:4)
如果您正在尝试对微模板进行插值,我为此目的喜欢Mustache.js。
答案 8 :(得分:3)
我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许你执行以下操作
{ 'userName': 'k Moe' }
将用数组项替换{0}和{1}并返回以下字符串
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
或者您可以使用对象键和值替换占位符,如下所示:
"this is a test string for stringInject"
答案 9 :(得分:2)
请勿查看此处提及的任何外部库,但Lodash已_.template()
,
https://lodash.com/docs/4.17.10#template
如果您已经使用了图书馆,那么值得一试,如果您没有使用Lodash,您可以随时从npm install lodash.template
开始挑选方法。你可以减少开销。
最简单的形式 -
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!'
我发现自定义分隔符最有趣。
答案 10 :(得分:1)
只需使用:
var util = require('util');
var value = 15;
var s = util.format("The variable value is: %s", value)
答案 11 :(得分:0)
我会使用反勾号``。
let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
但是,如果您在创建name1
时不认识msg1
。
例如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}
。
答案 12 :(得分:0)
创建类似于Java String.format()
的方法
StringJoin=(s, r=[])=>{
r.map((v,i)=>{
s = s.replace('%'+(i+1),v)
})
return s
}
使用
console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
答案 13 :(得分:0)
2020年和平报价:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
答案 14 :(得分:-1)
String.prototype.interpole = function () {
var c=0, txt=this;
while (txt.search(/{var}/g) > 0){
txt = txt.replace(/{var}/, arguments[c]);
c++;
}
return txt;
}
Uso:
var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
答案 15 :(得分:-2)
host
var hello = "foo";
console.log(我的字符串,你好)