How to build/concatenate strings in JavaScript?
P粉513316221
P粉513316221 2023-08-27 19:01:23
0
2
499
<p>Does JavaScript support replacement/interpolation? </p> <h3>Overview</h3> <hr /> <p>I'm working on a JavaScript project and as it gets bigger it's getting harder and harder to keep the strings in good shape. I would like to know what is the simplest and most traditional way to construct or build a string in JavaScript. </p> <p>My experience so far:</p> <blockquote> <p>As projects become more complex, string concatenation starts to look ugly and becomes harder to maintain. </p> </blockquote> <p>The most important thing at this point is simplicity and readability, think about a bunch of moving parts, not just 2-3 variables. </p> <p>Equally important, it is currently supported by major browsers (i.e. at least ES5). </p> <p>I know the JavaScript connection abbreviation: </p> <pre class="brush:php;toolbar:false;">var x = 'Hello'; var y = 'world'; console.log(x ', ' y);</pre> <p>There is also the String.concat function. </p> <p>I'm looking for something cleaner. </p> <p>Ruby and Swift do this in an interesting way. </p> <p><strong>Ruby</strong></p> <pre class="brush:php;toolbar:false;">var x = 'Hello' var y = 'world' print "#{x}, #{y}"</pre> <p><strong>Swift</strong></p> <pre class="brush:php;toolbar:false;">var x = "Hello" var y = "world" println("(x), (y)")</pre> <p>I thought there might be something similar in JavaScript, maybe something like sprintf.js. </p> <h3>Question</h3> <hr /> <p>Can this be done without a third-party library? If not, what can I use? </p>
P粉513316221
P粉513316221

reply all(2)
P粉244730625

I'm disappointed that no one in the other answers explained "best way" to mean "fastest way"...

I extracted two examples from here and added str. join() and str.reduce() from nishanths' answer above. Here are my results on Firefox 77.0.1 on Linux.


Note: I discovered while testing these that if I put str = str.concat() and str = directly before or after each other Between them, the second one always performs better... so I run these tests individually and comment on the results of the other tests...

Even so, their speeds would change a lot if I reran them, so I measured each 3 times.

1 character at a time:

  • str = str.concat(): 841, 439, 956 ms / 1e7
  • of concat()
  • ............str =:949, 1130, 664 milliseconds / 1e7 ='s
  • ......[].join(): There are 3350, 2911, 3522 ms / 1e7 characters in []
  • ...[].reduce(): 3954, 4228, 4547 ms / 1e7 characters in []

26 strings at a time:

  • str = str.concat(): 444, 744, 479 ms / 1e7
  • of concat()
  • ............str =1037, 473, 875 milliseconds / 1e7 ='s
  • ........[].join(): 2693, 3394, 3457 ms / 1e7 string in []
  • ......[].reduce(): 2782, 2770, 4520 ms / 1e7 string in []

So, whether appending 1 character at a time or appending 26 strings at a time:

  • Clear winner: basically a tie between str = str.concat() and str =
  • Obvious losers: [].reduce(), then [].join()

My code, easy to run in browser console:

{
  console.clear();

  let concatMe = 'a';
  //let concatMe = 'abcdefghijklmnopqrstuvwxyz';

  //[].join()
  {
    s = performance.now();
    let str = '', sArr = [];
    for (let i = 1e7; i > 0; --i) {
      sArr[i] = concatMe;
    }
    str = sArr.join('');
    e = performance.now();
    console.log(e - s);
    console.log('[].join(): ' + str);
  }

  //str +=
  {
    s = performance.now();
    let str = '';
    for (let i = 1e7; i > 0; --i) {
      str += concatMe;
    }
    e = performance.now();
    console.log(e - s);
    console.log('str +=: ' + str);
  }

  //[].reduce()
  {
    s = performance.now();
    let str = '', sArr = [];
    for (let i = 1e7; i > 0; --i) {
      sArr[i] = concatMe;
    }
    str = sArr.reduce(function(pre, next) {
      return pre + next;
    });
    e = performance.now();
    console.log(e - s);
    console.log('[].reduce(): ' + str);
  }

  //str = str.concat()
  {
    s = performance.now();
    let str = '';
    for (let i = 1e7; i > 0; --i) {
      str = str.concat(concatMe);
    }
    e = performance.now();
    console.log(e - s);
    console.log('str = str.concat(): ' + str);
  }

  'Done';
}
P粉412533525

Using ES6, you can use

  • Template string: p>

    var username = 'craig';
    console.log(`hello ${username}`);

ES5 and below:

  • Using Operator

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

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

Or, use the array method:

  • join( ..)

    var username = 'craig';
    var joined = ['hello', username].join(' ');
  • Or more exotically, 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template