考虑下面的代码:

var age = 3;

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

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


当前回答

自定义灵活插补:

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>

其他回答

从ES6开始,如果你想在对象键中做字符串插值,你会得到一个SyntaxError: expected属性名,得到'${'如果你做这样的事情:

let age = 3
let obj = { `${age}`: 3 }

你应该做以下事情:

let obj = { [`${age}`]: 3 }

警告:避免任何不允许您转义其自己的分隔符的模板系统。例如,使用此处提到的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(" ");

找不到我要找的东西,然后找到了

如果你使用的是Node.js,有一个内置的utipackage,它有一个format函数,工作方式是这样的:

util.format("Hello my name is %s", "Brent");
> Hello my name is Brent

巧合的是,在Node.js -中,这也被内置到console.log版本中

console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError

如果您想在console.log输出中插入,那么只需

console.log("Eruption 1: %s", eruption1);
                         ^^

这里,%s是所谓的“格式说明符”。log内置了这种插值支持。

当我不知道如何正确地表达,只想快速地得到一个想法时,我就会在很多语言中使用这种模式:

// JavaScript
let stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
    .replace(/{name}/g    ,'Inigo Montoya')
    .replace(/{action}/g  ,'killed')
    .replace(/{relation}/g,'father')
    ;

虽然不是特别高效,但我觉得它可读。它总是有效的,而且总是可用的:

' VBScript
dim template = "Hello, my name is {name}. You {action} my {relation}."
dim stringvalue = template
stringValue = replace(stringvalue, "{name}"    ,"Luke Skywalker")     
stringValue = replace(stringvalue, "{relation}","Father")     
stringValue = replace(stringvalue, "{action}"  ,"are")

总是

* COBOL
INSPECT stringvalue REPLACING FIRST '{name}'     BY 'Grendel Mother'
INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Son shoulder'
INSPECT stringvalue REPLACING FIRST '{action}'   BY 'made a gaping mortal-making wound upon.'