Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

What's the best way to do string building/concatenation in JavaScript?

Does JavaScript support substitution/interpolation?

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.

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.

It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).

I'm aware of the JS concatenation shorthand:

var x = 'Hello';
var y = 'world';
console.log(x + ', ' + y);

And of the String.concat function.

I'm looking for something a bit neater.

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)")

I was thinking that there might be something like that in JavaScript maybe something similar to sprintf.js.

Question


Can this be done without any third party library? If not, what can I use?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With ES6, you can use

ES5 and below:

  • use the + operator

    var username = 'craig';
    var joined = 'hello ' + username;
    
  • String's concat(..)

    var username = 'craig';
    var joined = 'hello '.concat(username);
    

Alternatively, use Array methods:

  • join(..):

    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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...