考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
试试kiwi吧,它是一个轻量级的JavaScript模块,用于字符串插值。
你可以这样做
Kiwi.compose("I'm % years old!", [age]);
or
Kiwi.compose("I'm %{age} years old!", {"age" : age});
其他回答
试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
Vsprintf接受一个参数数组并返回一个格式化的字符串。
自定义灵活插补:
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>
如果您想在console.log输出中插入,那么只需
console.log("Eruption 1: %s", eruption1);
^^
这里,%s是所谓的“格式说明符”。log内置了这种插值支持。
虽然模板可能最适合你描述的情况,但如果你有或想要你的数据和/或参数是可迭代/数组形式,你可以使用String.raw。
String.raw({
raw: ["I'm ", " years old!"]
}, 3);
将数据作为数组,可以使用展开操作符:
const args = [3, 'yesterday'];
String.raw({
raw: ["I'm ", " years old as of ", ""]
}, ...args);
在旧的浏览器中使用模板语法会失败,这对于创建供公众使用的HTML很重要。使用连接是乏味且难以阅读的,特别是当您有很多或很长的表达式时,或者如果您必须使用括号来处理数字和字符串项的混合(两者都使用+运算符)。
PHP扩展带引号的字符串,其中包含变量,甚至一些表达式,使用非常紧凑的符号:$a="颜色是$color";
在JavaScript中,可以编写一个有效的函数来支持这一点:var a=S('the color is ',color);,使用可变数量的参数。虽然在本例中没有连接的优势,但当表达式变长时,语法可能会更清晰。或者可以像在PHP中那样,使用JavaScript函数使用美元符号表示表达式的开始。
另一方面,编写一个有效的变通函数来为旧浏览器提供类似模板的字符串展开并不困难。可能已经有人这么做了。
最后,我认为sprintf(就像在C、c++和PHP中一样)可以用JavaScript编写,尽管它的效率要比其他解决方案低一些。