How to replace a character at a particular index in JavaScript ?
Last Updated :
28 Apr, 2023
To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below:
Approach 1: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index. This can be used to extract the parts of the string excluding the character to be replaced. The first part of the string can be extracted by using the starting index parameter as ‘0’ (which denotes the starting of the string) and the length parameter as the index where the character has to be replaced. The second part of the string can be extracted by using the starting index parameter as ‘index + 1’, which denotes the part of the string after the index of the character. The second parameter is omitted to get the whole string after it. The new string is created and concatenates the two parts of the string with the character to be replaced and added in between. This will create a new string with the character replaced at the index.
Syntax:
function replaceChar(origString, replaceChar, index) {
let firstPart = origString.substr(0, index);
let lastPart = origString.substr(index + 1);
let newString = firstPart + replaceChar + lastPart;
return newString;
}
Example: In this example, we are using the above-explained approach.
html
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to replace a character at a
particular index in JavaScript?
</b>
<p>
The character at the 8th index
would be replaced by "M".
</p>
<p>
Original string is: GeeksforGeeks
</p>
<p>
New String is:
<span class="output"></span>
</p>
<button onclick="changeText()">
Replace Character
</button>
<script>
function replaceChar(origString, replaceChar, index) {
let firstPart = origString.substr(0, index);
let lastPart = origString.substr(index + 1);
let newString =
firstPart + replaceChar + lastPart;
return newString;
}
function changeText() {
originalText = "GeeksforGeeks";
charReplaced =
replaceChar(originalText, "M", 8);
document.querySelector('.output').textContent
= charReplaced;
}
</script>
Output:
How to replace a character at a particular index in JavaScript ?
Approach 2:Converting the string to an array and replacing the character at the index: The string is converted to an array using the split() method with the separator as a blank character (“”). This will split the string into an array and make every character accessible as an index of the array. The character which has to be replaced can then be simply assigned to the corresponding index of the array. The array is joined back into a string using the join() method with the separator as a blank character (“”). This will create a new string with the character replaced at the index.
Syntax:
function replaceChar(origString, replaceChar, index) {
let newStringArray = origString.split("");
newStringArray[index] = replaceChar;
let newString = newStringArray.join("");
return newString;
}
Example: In this example, we are using the above-explained approach.
html
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to replace a character at a
particular index in JavaScript?
</b>
<p>
The character at the 8th index
would be replaced by "M".
</p>
<p>
Original string is: GeeksforGeeks
</p>
<p>
New String is:
<span class="output"></span>
</p>
<button onclick="changeText()">
Replace Character
</button>
<script>
function replaceChar(origString, replaceChar, index) {
let newStringArray = origString.split("");
newStringArray[index] = replaceChar;
let newString = newStringArray.join("");
return newString;
}
function changeText() {
originalText = "GeeksforGeeks";
charReplaced =
replaceChar(originalText, "M", 8);
document.querySelector('.output').textContent
= charReplaced;
}
</script>
Output:
How to replace a character at a particular index in JavaScript ?
Using the slice() method: The slice() method is used to get a part string from a given starting index to another index. This method is the same as the first method but in place of substr() method we use slice method.
HTML
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to replace a character at a
particular index in JavaScript?
</b>
<p>
The character at the 8th index
would be replaced by "M".
</p>
<p>
Original string is: GeeksforGeeks
</p>
<p>
New String is:
<span class="output"></span>
</p>
<button onclick="changeText()">
Replace Character
</button>
<script>
function replaceChar(origString, replaceChar, index)
{
let firstPart = origString.slice(0, index);
let lastPart = origString.slice(index + 1);
let newString =
firstPart + replaceChar + lastPart;
return newString;
}
function changeText() {
originalText = "GeeksforGeeks";
charReplaced =
replaceChar(originalText, "M", 8);
document.querySelector('.output').textContent
= charReplaced;
}
</script>
Output:
How to replace a character at a particular index in JavaScript ?
Similar Reads
How to replace lowercase letters with an other character in JavaScript ?
Given a string and the task is to replace all lowercase letters from a string with the other characters in JavaScript. There are some approaches to replace the character that are described below: JavaScript replace() Method: This method searches a string for a defined value, or a regular expression,
2 min read
How to remove portion of a string after certain character in JavaScript ?
Given a URL and the task is to remove a portion of URL after a certain character using JavaScript. split() method: This method is used to split a string into an array of substrings, and returns the new array. Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It spe
3 min read
JavaScript - Insert Character at a Given Position in a String
These are the following approaches to insert a character at a given position: 1. Using String Concatenation with SlicingSplit the string into two partsâbefore and after the positionâand concatenate the character in between.JavaScriptlet str = "Hello GFG"; let ch = "!"; let idx = 5; let res = str.sli
1 min read
JavaScript - Add a Character to the End of a String
These are the following ways to insert a character at the end of the given string:1. Using ConcatenationWe can use the + operator or template literals to append the character.JavaScriptlet str = "Hello GFG"; let ch = "!"; let res = str + ch; console.log(res); OutputHello GFG! 2. Using Template Liter
2 min read
JavaScript - Delete Character at a Given Position in a String
These are the following ways to Delete Character at a Given Position in a String:1. Using slice() MethodThe slice() method allows you to extract portions of a string. By slicing before and after the target position, you can omit the desired character.JavaScriptlet str = "Hello GFG"; let idx = 5; let
1 min read
How to Iterate Over Characters of a String in JavaScript ?
There are several methods to iterate over characters of a string in JavaScript. 1. Using for LoopThe classic for loop is one of the most common ways to iterate over a string. Here, we loop through the string by indexing each character based on the string's length.Syntaxfor (statement 1 ; statement 2
2 min read
Replace Duplicate Occurrence in a String in JavaScript
JavaScript String is a sequence of characters, typically used to represent text. It is useful to clean up strings by removing any duplicate characters. This can help normalize data and reduce unnecessary bloat. There are several ways to replace duplicate occurrences in a given string using different
3 min read
How to replace multiple characters in a string in PHP ?
A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP.Using the str_repla
3 min read
How to replace a portion of strings with another value in JavaScript ?
In JavaScript, replacing a portion of strings with another value involves using the `replace()` method or regular expressions. This process is essential for text manipulation tasks like formatting, sanitization, or dynamic content generation in web development and data processing applications. We ca
3 min read
Print ASCII Value of a Character in JavaScript
ASCII is a character encoding standard that has been a foundational element in computing for decades. It is used to define characters in a computer. There is a huge table of ASCII values. To print the values in JavaScript In this post, we print the ASCII code of a specific character. One can print t
2 min read