568

我知道在 PHP 中我们可以做这样的事情:

$hello = "foo";
$my_string = "I pity the $hello";

输出:"I pity the foo"

我想知道在 JavaScript 中是否也可以做到同样的事情。在字符串中使用变量而不使用连接——它看起来更简洁优雅。

4

16 回答 16

1033

您可以利用模板文字并使用以下语法:

`String text ${expression}`

模板文字用反引号 (` `)(重音)而不是双引号或单引号括起来。

此功能已在 ES2015 (ES6) 中引入。

例子

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

这有多整洁?

奖金:

它还允许在 javascript 中使用多行字符串而无需转义,这对于模板非常有用:

return `
    <div class="${foo}">
         ...
    </div>
`;

浏览器支持

由于旧版浏览器(主要是 Internet Explorer)不支持这种语法,您可能需要使用Babel /Webpack 将代码转换为 ES5 以确保它可以在任何地方运行。


边注:

从 IE8+ 开始,您可以在内部使用基本的字符串格式console.log

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
于 2015-01-22T12:37:22.230 回答
173

Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge 之前,不,这在 javascript 中是不可能的。您将不得不求助于:

var hello = "foo";
var my_string = "I pity the " + hello;
于 2010-07-21T21:30:26.997 回答
44

Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge 之前,没有。尽管您可以尝试sprintf for JavaScript以达到一半:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
于 2010-07-21T21:32:27.197 回答
40

好吧,您可以这样做,但这不是一般的

'I pity the $fool'.replace('$fool', 'fool')

如果您真的需要,您可以轻松编写一个智能地执行此操作的函数

于 2010-07-21T21:34:23.697 回答
21

<ES6的完整且可以使用的答案:

 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'});

如果您在>ES6上,那么您还可以执行以下操作:

let first = 'Neo'; 
`My firstname is ${first}`; 
于 2017-07-05T17:12:23.040 回答
11

你可以使用这个 javascript 函数来做这种模板。无需包含整个库。

function createStringFromTemplate(template, variables) {
    return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
        return variables[varName];
    });
}

createStringFromTemplate(
    "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
    {
        list_name : "this store",
        var1      : "FOO",
        var2      : "BAR",
        var3      : "BAZ"
    }
);

输出"I would like to receive email updates from this store FOO BAR BAZ."

使用函数作为 String.replace() 函数的参数是 ECMAScript v3 规范的一部分。有关更多详细信息,请参阅此 SO 答案

于 2017-02-07T21:47:25.313 回答
10

如果你喜欢写 CoffeeScript,你可以这样做:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript 实际上是 javascript,但语法要好得多。

有关 CoffeeScript 的概述,请查看此初学者指南

于 2015-02-13T10:33:02.380 回答
7

我会使用反勾号``。

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}为他的价值。

于 2019-10-23T09:39:45.643 回答
6

我写了这个 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" 
于 2017-07-08T08:12:53.537 回答
4

如果您尝试为微模板进行插值,我喜欢Mustache.js用于此目的。

于 2010-07-21T21:32:48.880 回答
3

看不到这里提到的任何外部库,但 Lodash 有_.template()

https://lodash.com/docs/4.17.10#template

如果您已经在使用该库,那么值得一试,如果您没有使用 Lodash,您可以随时从 npm 中挑选方法,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!'

我发现自定义分隔符最有趣。

于 2018-05-14T19:14:27.080 回答
3

只需使用:

var util = require('util');

var value = 15;
var s = util.format("The variable value is: %s", value)
于 2020-03-01T02:41:24.760 回答
0
String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

使用:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
于 2019-03-11T03:08:43.327 回答
0

创建类似于String.format()Java的方法

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'
于 2019-12-11T19:26:00.973 回答
0

2020年和平报价:

Console.WriteLine("I {0} JavaScript!", ">:D<");

console.log(`I ${'>:D<'} C#`)
于 2020-01-28T15:09:41.017 回答
-5

var hello = "foo";

var my_string ="I pity the";

控制台日志(我的字符串,你好)

于 2019-11-22T18:57:04.460 回答