JavaScript - Add Characters to a String
Here are the various approaches to add characters to a string in JavaScript
Using the + Operator - Most Popular
The + operator is the simplest way to add characters to a string. It concatenates one or more strings or characters without modifying the original string.
const s1 = "Hello";
const s2 = s1 + " World!";
console.log(s2);
Output
Hello World!
Using concat() Method
The concat() method returns a new string that combines the original string with the specified values.
const s1 = "Hello";
const s2 = s1.concat(" World!");
console.log(s2);
Output
Hello World!
Using Template Literals
We can use Template Literals to add characters to strings by adding expressions within backticks. This approach useful when you need to add multiple characters or variables.
const s1 = "Hello";
const s2 = `${s1} World!`;
console.log(s2);
Output
Hello World!
Using slice() Method
The slice() method is used to add characters at specific positions in a string by slicing and then recombining parts of the original string.
const s1 = "Hello";
const s2 = "Hi, ".slice(0) + s1;
console.log(s2);
Output
Hi, Hello
Using padEnd() Method
The padEnd() method appends characters to the end of a string until it reaches a specified length.
const s1 = "Hello";
// Add characters to reach a specific length
const s2 = s1.padEnd(s1.length + 7, " World!");
console.log(s2);
Output
Hello World!
Using Array.prototype.join() Method
We can convert the strings to array and then use join() to add characters to a string.
const s1 = "Hello";
const s2 = ["Hi", s1, "World!"].join(" ");
console.log(s2);
Output
Hi Hello World!
Using substr() Method
Although substr() is generally used to extract substrings, it can also be used when adding characters by splitting and recombining the original string.
const s1 = "Hello";
const s2 = s1.substr(0) + " Everyone!";
console.log(s2);
Output
Hello Everyone!
Using substring() Method
The substring() method can slice portions of the original string and combine them with new characters.
const s1 = "Hello";
const s2 = "Hi, " + s1.substring(0);
console.log(s2);
Output
Hi, Hello