JavaScript - Add a Character to the End of a String
Last Updated : 20 Nov, 2024
Improve
These are the following ways to insert a character at the end of the given string:
1. Using Concatenation
We can use the + operator or template literals to append the character.
let str = "Hello GFG";
let ch = "!";
let res = str + ch;
console.log(res);
Output
Hello GFG!
2. Using Template Literals
String concatenation using + or template literals is an effective way to insert a character at the end of a string. This method creates a new string with the desired modification without altering the original string (since strings are immutable in JavaScript).
let str = "Hello, World!";
let ch = "*";
let res = `${str}${ch}`;
console.log(res);
Output
Hello, World!*
3. Using slice() Method
The slice method to extract the original string and append the new character.
let str = "Hello GFG";
let ch = "!";
// Slices the entire string and appends the character
let res = str.slice(0) + ch;
console.log(res);
Output
Hello GFG!
4. Using Using splice() Method (Array-Based)
Convert the string to an array, use splice to insert the character, and join the array back into a string.
let str = "Hello GFG";
let ch = "!";
// Convert string to array
let arr = str.split("");
// Insert character at the end
arr.splice(arr.length, 0, ch);
// Convert array back to string
let res = arr.join("");
console.log(res);
Output
Hello GFG!