Skip to content

String building/concatenation in JavaScript

In this article, we will look some of the commons ways to building / concatenating a String in JavaScript. JavaScript contains a number of features for manipulating strings which are discussed below.

1. ES6 Template Literals

Also referred to be as Template String. This provides more flexible and easier to read string. Instead of using single quote(‘) and double quote(“) this uses the ` that is backtick.

let str = `Hai Poopcoder!`;

Template literals considers the line break in source code, so newline character no needed for this method.

let Str = `Hai Poopcoder!
How are you?`;

Substitutions is more easy in this method.

let str1 = `Poopcoder!`;
let str2 = `Hai "${str1 }"`;

2. + Operator

This will join the string. The result of this is a variable called joined. We can join as many as we like. We can user \n to add new line in the String.

let str = 'Hai, ' + 'Poopcoder! ' + '\n How are you?';
//Escape new line uisng \
let str = 'Hai, ' + 'Poopcoder! ' + '\
How are you?';

3. ES1 concat() method

This will return the new string containing the joined text. Can pass multiple string to concatenate.

let str1 = 'Hai, ';
let str2 = 'Poopcoder!';
let str3 = 'Have a nice day!';
let str3 = str1.concat(str2);
let str4 = str1.concat(str2, str3);

I would recommend to get used to using the Template literals to building the string. They are well supported in modern browsers, but the back-tick character is not recognized as a Valid Character in IE11.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.