如何在JavaScript中插入变量而没有连接?

DMi*_*Min 336 javascript string variables string-interpolation

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

$hello = "foo";
$my_string = "I pity the $hello";
Run Code Online (Sandbox Code Playgroud)

输出: "I pity the foo"

我想知道在JavaScript中是否也可以使用同样的东西.在不使用串联的情况下在字符串中使用变量 - 它看起来更简洁和优雅.

bfo*_*met 589

从Firefox 34/Chrome 41/Safari 9/Microsoft Edge开始,您可以使用名为Template Literals的ES2015/ES6功能并使用以下语法:

`String text ${expression}`
Run Code Online (Sandbox Code Playgroud)

模板文字由后面的勾号(``)(重音符号)括起来,而不是双引号或单引号.

例:

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

这有多整洁?

奖金:

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

return `
    <div class="${foo}">
         ...
    </div>
`;
Run Code Online (Sandbox Code Playgroud)

浏览器支持:

由于旧版浏览器(Internet Explorer和Safari <= 8)不支持此语法,您可能希望使用Babel将代码转换为ES5以确保它可以在任何地方运行.


边注:

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

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
Run Code Online (Sandbox Code Playgroud)

  • 不要错过模板字符串用后标记(\`)而不是普通引号字符分隔的事实.`"$ {foo}"`字面上是$ {foo}`\`$ {foo} \``是你真正想要的 (44认同)
  • 背部蜱虫是救星。 (2认同)

Sar*_*raz 164

Firefox 34/Chrome 41/Safari 9/Microsoft Edge之前,nope,这在javascript中是不可能的.你不得不诉诸:

var hello = "foo";
var my_string = "I pity the " + hello;
Run Code Online (Sandbox Code Playgroud)

  • 很快就可以在javascript(ES6)中使用Template Strings,请参阅下面的详细解答. (2认同)

Jus*_*ier 40

Firefox 34/Chrome 41/Safari 9/Microsoft Edge之前,没有.虽然您可以尝试使用sprintf for JavaScript来获得一半:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
Run Code Online (Sandbox Code Playgroud)


Sco*_*den 29

你能做到这一点,但它不是特别的

'I pity the $fool'.replace('$fool', 'fool')
Run Code Online (Sandbox Code Playgroud)

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

  • 当您需要将模板字符串存储在数据库中并按需处理时,此答案很好 (2认同)

mom*_*omo 10

完整答案,随时可用:

 var Strings = {
        create : (function() {
                var regexp = /{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};
Run Code Online (Sandbox Code Playgroud)

打电话给

Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
Run Code Online (Sandbox Code Playgroud)

要将它附加到String.prototype:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
Run Code Online (Sandbox Code Playgroud)

然后用作:

"My firstname is ${first}".create({first:'Neo'});
Run Code Online (Sandbox Code Playgroud)


bfo*_*met 9

如果您想编写CoffeeScript,您可以这样做:

hello = "foo"
my_string = "I pity the #{hello}"
Run Code Online (Sandbox Code Playgroud)

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

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


Eri*_*and 9

您可以使用此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"
    }
);
Run Code Online (Sandbox Code Playgroud)

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

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


小智 7

我会使用反勾号``。

let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
Run Code Online (Sandbox Code Playgroud)

但是,如果您不知道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'
Run Code Online (Sandbox Code Playgroud)

它将取代${name2}他的价值。


tjc*_*key 5

我写了这个 npm 包 stringinject https://www.npmjs.com/package/stringinject它允许您执行以下操作

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
Run Code Online (Sandbox Code Playgroud)

这将用数组项替换 {0} 和 {1} 并返回以下字符串

"this is a test string for stringInject"
Run Code Online (Sandbox Code Playgroud)

或者您可以用对象键和值替换占位符,如下所示:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 
Run Code Online (Sandbox Code Playgroud)