Home  >  Q&A  >  body text

How to build/concatenate strings in JavaScript?

<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粉513316221P粉513316221420 days ago474

reply all(2)I'll reply

  • P粉244730625

    P粉2447306252023-08-28 15:08:49

    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';
    }

    reply
    0
  • P粉412533525

    P粉4125335252023-08-28 14:12:16

    Using ES6, you can use

    • Template string:

      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, < code>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

    reply
    0
  • Cancelreply