考虑下面的代码:

var age = 3;

console.log("I'm " + age + " years old!");

除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?


当前回答

试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

Vsprintf接受一个参数数组并返回一个格式化的字符串。

其他回答

替换更多的ES6版本的@Chris Nielsen的帖子。

String.prototype.supplant = function (o) {
  return this.replace(/\${([^\${}]*)}/g,
    (a, b) => {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};

string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";

string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."

自定义灵活插补:

var sourceElm = document.querySelector('input') // interpolation callback const onInterpolate = s => `<mark>${s}</mark>` // listen to "input" event sourceElm.addEventListener('input', parseInput) // parse on window load parseInput() // input element parser function parseInput(){ var html = interpolate(sourceElm.value, undefined, onInterpolate) sourceElm.nextElementSibling.innerHTML = html; } // the actual interpolation function interpolate(str, interpolator = ["{{", "}}"], cb){ // split by "start" pattern return str.split(interpolator[0]).map((s1, i) => { // first item can be safely ignored if( i == 0 ) return s1; // for each splited part, split again by "end" pattern const s2 = s1.split(interpolator[1]); // is there's no "closing" match to this part, rebuild it if( s1 == s2[0]) return interpolator[0] + s2[0] // if this split's result as multiple items' array, it means the first item is between the patterns if( s2.length > 1 ){ s2[0] = s2[0] ? cb(s2[0]) // replace the array item with whatever : interpolator.join('') // nothing was between the interpolation pattern } return s2.join('') // merge splited array (part2) }).join('') // merge everything } input{ padding:5px; width: 100%; box-sizing: border-box; margin-bottom: 20px; } *{ font: 14px Arial; padding:5px; } <input value="Everything between {{}} is {{processed}}" /> <div></div>

警告:避免任何不允许您转义其自己的分隔符的模板系统。例如,使用此处提到的supplant()方法将无法输出以下内容。

“多亏了我的年龄变量,我才3岁。”

简单的插值可能适用于小型的自包含脚本,但通常会出现这种设计缺陷,限制任何重要的使用。老实说,我更喜欢DOM模板,比如:

<div> I am <span id="age"></span> years old!</div>

$('#age').text(3)

另外,如果你只是厌倦了字符串连接,总有替代语法:

var age = 3;
var str = ["I'm only", age, "years old"].join(" ");

扩展Greg Kindel的第二个答案,你可以写一个函数来消除一些样板文件:

var fmt = {
    join: function() {
        return Array.prototype.slice.call(arguments).join(' ');
    },
    log: function() {
        console.log(this.join(...arguments));
    }
}

用法:

var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');

虽然模板可能最适合你描述的情况,但如果你有或想要你的数据和/或参数是可迭代/数组形式,你可以使用String.raw。

String.raw({
  raw: ["I'm ", " years old!"]
}, 3);

将数据作为数组,可以使用展开操作符:

const args = [3, 'yesterday'];
String.raw({
  raw: ["I'm ", " years old as of ", ""]
}, ...args);