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

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

输出:"I pity the foo"

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


当前回答

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"

其他回答

在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,没有。尽管你可以尝试JavaScript的sprintf来实现:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);

简单的使用方法:

var util = require('util');

var value = 15;
var s = util.format("The variable value is: %s", value)

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

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

use

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'

完整且随时可用的回答<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);
}

然后使用as:

"My firstname is ${first}".create({first:'Neo'});

如果你在>ES6上,那么你也可以这样做:

let first = 'Neo'; 
`My firstname is ${first}`; 

我写了这个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"