在JavaScript中进行字符串构建/连接的最佳方法是什么? [英] What's the best way to do string building/concatenation in JavaScript?
问题描述
JavaScript是否支持替换/插值?
Does JavaScript support substitution/interpolation?
我正在研究一个JS项目,随着它越来越大,保持良好的字符串形状变得越来越难。我想知道在JavaScript中构造或构建字符串的最简单和最常规的方法是什么。
I'm working on a JS project, and as it's getting bigger, keeping strings in good shape is getting a lot harder. I'm wondering what's the easiest and most conventional way to construct or build strings in JavaScript.
到目前为止我的经验:
当项目变得更复杂时,字符串连接开始变得难看并且变得更难维护。
String concatenation starts looking ugly and becomes harder to maintain as the project becomes more complex.
在这一点上最重要的是简洁性和可读性,想想一堆活动部分,而不仅仅是2-3个变量。
The most important this at this point is succinctness and readability, think a bunch of moving parts, not just 2-3 variables.
同样重要的是它得到专业的支持截至今天的浏览器(即至少支持ES5)。
It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).
我知道JS连接的简写:
I'm aware of the JS concatenation shorthand:
var x = 'Hello';
var y = 'world';
console.log(x + ', ' + y);
String.concat 函数。
我正在寻找有点整洁。
Ruby和Swift以一种有趣的方式做到这一点。
Ruby and Swift do it in an interesting way.
Ruby
var x = 'Hello'
var y = 'world'
print "#{x}, #{y}"
Swift
var x = "Hello"
var y = "world"
println("\(x), \(y)")
我以为在JavaScript中可能有类似的东西 sprintf.js 。
I was thinking that there might be something like that in JavaScript maybe something similar to sprintf.js.
这可以在没有任何第三方库的情况下完成吗?如果没有,我可以使用什么?
Can this be done without any third party library? If not, what can I use?
推荐答案
使用ES6,你可以使用
With ES6, you can use
var username = 'craig';
console.log(`hello ${username}`);
ES5及以下:
-
使用
+
运算符
var username = 'craig';
var joined = 'hello ' + username;
字符串 concat(..)
var username = 'craig';
var joined = 'hello '.concat(username);
或者,使用数组方法:
-
join(..)
:
var username = 'craig';
var joined = ['hello', username].join(' ');
甚至更高级, reduce(..)
结合任何上述内容:
Or even fancier, reduce(..)
combined with any of the above:
var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
var b = a.reduce(function(pre, next) {
return pre + ' ' + next;
});
console.log(b); // hello world and the milky way
这篇关于在JavaScript中进行字符串构建/连接的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!