I have a string, let\'s say Hello world
and I need to replace the char at index 3. How can I replace a char by specifying a index?
var str = \"h
Generalizing Afanasii Kurakin's answer, we have:
function replaceAt(str, index, ch) {
return str.replace(/./g, (c, i) => i == index ? ch : c);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
Let's expand and explain both the regular expression and the replacer function:
function replaceAt(str, index, newChar) {
function replacer(origChar, strIndex) {
if (strIndex === index)
return newChar;
else
return origChar;
}
return str.replace(/./g, replacer);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
The regular expression .
matches exactly one character. The g
makes it match every character in a for loop. The replacer
function is called given both the original character and the index of where that character is in the string. We make a simple if
statement to determine if we're going to return either origChar
or newChar
.