Open In App

JavaScript - Add a Character to the Beginning of a String

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to insert a character at the beginning of the given string:

1. Using String Concatenation

Directly prepend the character using the + operator or template literals.

JavaScript
let str = "Hello, World!";
let ch = "*";
let res = ch + str;
console.log(res); 

Output
*Hello, World!

2. Using Template Literals

String concatenation using + or template literals is an effective way to insert a character at the beginning of a string. This method creates a new string with the desired modification without altering the original string (since strings are immutable in JavaScript).

JavaScript
let str = "Hello, World!";
let ch = "*";
let res = `${ch}${str}`;
console.log(res);

Output
*Hello, World!

3. Using slice() Method

Extract the original string and append the new character to it by the use of slice() method.

JavaScript
let str = "Hello, World!";
let ch = "*";
 // Slice the entire string and prepend
let res = ch + str.slice(0);
console.log(res); 

Output
*Hello, World!

4. Using Using splice() Method (Array-Based)

Convert the string to an array (as strings are immutable in JavaScript), use splice to insert the character at the beginning, and join it back into a string.

JavaScript
let str = "Hello, World!";
let ch = "*";
 // Convert string to array
let arr = str.split("");

// Insert the character at index 0
arr.splice(0, 0, ch); 
// Convert array back to string
let res = arr.join(""); 
console.log(res); 

Output
*Hello, World!

Next Article

Similar Reads