How To Replace The First Character In A String In JavaScript

Replace the First Character in a String in JavaScript

In this article, we will show you how to replace the first character in a string in JavaScript in many different ways like using the replace() method and using the slice() method. Start reading the detailed article.

Replace the first character in a string in JavaScript

Using the replace() method

The simple and easy way is using the replace() method to do it. This method has been introduced by us here. Please read it to get more information.

Code example:

In this example, we create the myString variable l in lowercase. Then we call the replace method with .^ regular expression and global g to replace to uppercase.

const myString = 'learnShareIT';
console.log("My string is: ", myString);

// Using the replace() method with ^. to replace l to L character
const newString = myString.replace(/^./g, 'L');
console.log("After replacing the first occurrence of character: ", newString); // LearnShareIT

Output

My string is:  learnShareIT
After replacing the first occurrence of character:  LearnShareIT

Using string slice() with + operator

The second way is using the slice() method with the + operator. This method will return the slow copy of a portion of an array into a new array object. The original array will not be modified. Let’s see the code example below:

const myString = 'learnShareIT';
console.log("My string is: ", myString);

// Using the slice() method with -1 and + 'L' operator
const newString = 'L' + myString.slice(1);
console.log("After replacing the first occurrence of character: ", newString); // LearnShareIT

Output

My String is: learnShareIT
After replacing the first occurrence of character: LearnShareIT

Using string slice() with concat() method

The last way is using the concat() method and string slice() method. The concat() method will return a new string containing the combined strings. And using the string slice method to replace the first occurrence character in myString.

Example:

const myString = 'learnShareIT';
console.log("My string is: ", myString);

// Using the string slice() with concat() method
const newString = 'L'.concat(myString.slice(1));
console.log("After replacing the first occurrence of character: ", newString); // LearnShareIT

Output

My string is:  learnShareIT
After replacing the first occurrence of character:  LearnShareIT

Summary

Hopefully, through this article, you can choose for yourself the best way to replace the first character in a string in JavaScript. For us, using the replace() method to solve this problem is the best way to solve this problem. Have a nice day and thank for your reading!

Maybe you are interested:

Leave a Reply

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