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:
1 2 3 4 5 6 | let name = 'Alice'; let hello = `Hello ${name}` console.log(hello); // => Hello Alice |
- Assuming that we do not use template string so that if the string, we have the following example:
1 2 | let str = "Hi, I'm" + name; |
- And the result returns:
1 2 3 | console.log(str); // => Hi, I'mAlice |
- If using template string:
1 2 | let str = `Hi, I'm ${name}` |
- The following results:
1 2 3 | console.log(str) // => Hi, I'm Alice |
- 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.
1 2 3 4 5 6 7 8 9 10 11 | const arr = ["Kim", "Mộc", "Thuỷ", "Hỏa", "Thổ"]; console.log(arr.join()); // => Kim, Mộc, Thủy, Hỏa, Thổ console.log(arr.join(" ")) // => Kim Mộc Thủy Hỏa Thổ console.log(arr.join("-")) // => Kim-Mộc-Thủy-Hỏa-Thổ |
3. Use concat ()
- concat () : Used to concatenate 2 or more strings together
1 2 3 4 5 6 7 8 9 | let str1 = "Hello"; let str3 = "World!"; console.log(str1.concat(' ', str2)) // => Hello World! console.log(str1.concat('-', str2)) // => Hello-World! |
4. Use the ‘+’ operator
- Using the ‘+’ operator, we can create a new string or manipulate an existing string.
1 2 3 4 5 6 7 8 | let ironMan = "Iron Man "; let captain = "Captain America "; let thor = "Thor"; let newStr = "Hello " + ironMan + captain + thor; console.log(newStr); // => Hello Iron Man Captain America Thor |
1 2 3 4 5 6 | let oldStr = "Hello World!" oldStr += " Hello Sun*" console.log(oldStr) // => Hello World! Hello Sun* |
5. References
- Template string: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals
- Join: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join
- Concat: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
- https://medium.com/dailyjs/4-ways-to-combine-strings-in-javascript-b1de5302fdaa