Some ways to concatenate strings in JavaScript

Tram Ho

In this article, I will give a way to concatenate in Javascript, hopefully it will make your code shorter and easier to read.

1. Use the template string

  • Template string is a feature in ES6, its syntax allows us to write expressions right inside the string . In it, instead of using a pair of “” or around the string, use a pair of . For better understanding, I have the following example:

  • Assuming that we do not use template string so that if the string, we have the following example:

  • And the result returns:

  • If using template string:

  • The following results:

  • Thus, when using the template string, we will easily visualize how the string will be printed to the screen, the code will be easy to read and maintain.

2. Use join ()

  • join () : is a method that creates a string by concatenating the elements in an array, by default the elements in the string will be separated by commas, or can be specified.

3. Use concat ()

  • concat () : Used to concatenate 2 or more strings together

4. Use the ‘+’ operator

  • Using the ‘+’ operator, we can create a new string or manipulate an existing string.

5. References

Share the news now

Source : Viblo