在 JavaScript 中进行字符串构建/连接的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31845895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to do string building/concatenation in JavaScript?
提问by MrHaze
Does JavaScript support substitution/interpolation?
JavaScript 是否支持替换/插值?
Overview
概述
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.
我正在做一个 JS 项目,随着它变得越来越大,保持字符串的良好状态变得越来越困难。我想知道在 JavaScript 中构造或构建字符串的最简单和最传统的方法是什么。
My experience so far:
到目前为止我的经验:
String concatenation starts looking ugly and becomes harder to maintain as the project becomes more complex.
随着项目变得越来越复杂,字符串连接开始看起来很丑陋,并且变得更难维护。
The most important this at this point is succinctness and readability, think a bunch of moving parts, not just 2-3 variables.
在这一点上最重要的是简洁和可读性,想想一堆活动的部分,而不仅仅是 2-3 个变量。
It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).
到目前为止,主流浏览器都支持它也很重要(即至少支持 ES5)。
I'm aware of the JS concatenation shorthand:
我知道 JS 连接速记:
var x = 'Hello';
var y = 'world';
console.log(x + ', ' + y);
And of the String.concatfunction.
以及String.concat函数。
I'm looking for something a bit neater.
我正在寻找更整洁的东西。
Ruby and Swift do it in an interesting way.
Ruby 和 Swift 以一种有趣的方式做到了这一点。
Ruby
红宝石
var x = 'Hello'
var y = 'world'
print "#{x}, #{y}"
Swift
迅速
var x = "Hello"
var y = "world"
println("\(x), \(y)")
I was thinking that there might be something like that in JavaScript maybe something similar to sprintf.js.
我在想 JavaScript 中可能有类似的东西,可能类似于sprintf.js。
Question
题
Can this be done without any third party library? If not, what can I use?
这可以在没有任何第三方库的情况下完成吗?如果没有,我可以使用什么?
回答by nishanths
With ES6, you can use
使用 ES6,您可以使用
var username = 'craig'; console.log(`hello ${username}`);
var username = 'craig'; console.log(`hello ${username}`);
ES5 and below:
ES5及以下:
use the
+
operatorvar username = 'craig'; var joined = 'hello ' + username;
String's
concat(..)
var username = 'craig'; var joined = 'hello '.concat(username);
使用
+
运算符var username = 'craig'; var joined = 'hello ' + username;
字符串的
concat(..)
var username = 'craig'; var joined = 'hello '.concat(username);
Alternatively, use Array methods:
或者,使用数组方法:
var username = 'craig'; var joined = ['hello', username].join(' ');
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
var username = 'craig'; var joined = ['hello', username].join(' ');
甚至更高级,
reduce(..)
结合以上任何一项: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
回答by rrowland
var descriptor = 'awesome';
console.log(`ES6 is ${descriptor}!`);
More: https://developers.google.com/web/updates/2015/01/ES6-Template-Strings?hl=en
更多:https: //developers.google.com/web/updates/2015/01/ES6-Template-Strings?hl=en
回答by Culme
I think replace()deserves mentioning here.
我认为replace()在这里值得一提。
During some conditions, the replace method can serve you well when building strings. Specifically, obviously, when your injecting a dynamic part into an otherwise static string. Example:
在某些情况下,replace 方法在构建字符串时可以很好地为您服务。具体来说,显然,当您将动态部分注入其他静态字符串时。例子:
var s = 'I am {0} today!';
var result = s.replace('{0}', 'hungry');
// result: 'I am hungry today!'
The placeholder which to replace can obviously be anything. I use "{0}", "{1}" etc out of habit from C#. It just needs to be unique enough not to occur in the string other than where intended.
要替换的占位符显然可以是任何东西。我出于 C# 的习惯使用“{0}”、“{1}”等。它只需要足够独特,不会出现在除预期之外的字符串中。
So, provided we can fiddle with the string parts a bit, OPs example could be solved like this too:
因此,只要我们可以稍微处理一下字符串部分,OP 示例也可以这样解决:
var x = 'Hello {0}';
var y = 'World';
var result = x.replace('{0}', y);
// result: 'Hello World'. -Oh the magic of computing!
Reference for "replace": https://www.w3schools.com/jsreF/jsref_replace.asp
回答by Bla...
You could use Coffeescript, it's made to make javascript code more concise.. For string concatenation, you could do something like this:
您可以使用Coffeescript,它可以使 javascript 代码更加简洁。对于字符串连接,您可以执行以下操作:
first_name = "Marty"
full_name = "#{first_name} McFly"
console.log full_name
Maybe you can start hereto see what's offered by coffescript..
也许你可以从这里开始看看 coffescript 提供了什么..
回答by Script47
You could use the concat
function.
您可以使用该concat
功能。
var hello = "Hello ";
var world = "world!";
var res = hello.concat(world);