Replacing character at a particular index with a string in Javascript , Jquery
30,192
Solution 1
Strings are immutable in Javascript - you can't modify them "in place".
You'll need to cut the original string up, and return a new string made out of all of the pieces:
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
NB: I didn't add this to String.prototype
because on some browsers performance is very bad if you add functions to the prototype
of built-in types.
Solution 2
Or you could do it this way, using array functions.
var a='I am a man'.split('');
a.splice.apply(a,[7,1].concat('wom'.split('')));
console.log(a.join(''));//<-- I am a woman

Author by
Bobby Francis Joseph
Updated on May 29, 2020Comments
-
Bobby Francis Joseph about 3 years
Is it possible to replace the a character at a particular position with a string
Let us say there is say a string :
"I am a man"
I want to replace character at 7 with the string
"wom"
(regardless of what the original character was).The final result should be :
"I am a woman"