Change a Character in a string - setCharAt() Function
How do you change a character in a string in JavaScript? It's not possible! So I decided to make a small function to do it. In any other language, this code will work...
var str = 'Hello World';
str[4] = ',';
alert(str);//Shows 'Hell, World'
But not in javascript. So I have come up with a simple setCharAt function that will do this for you.
function setCharAt(str,index,char) {
if(index > str.length-1) return str;
return str.substr(0,index) + char + str.substr(index+1);
}
//Demo
var str = 'Hello World';
str = setCharAt(str,4,',');
alert(str);
- The first argument(
str) is the string in which the replacement must be made - The second argument(
index) is the index of the character to be replaced - The third argument(
char) is the new character that should be inserted.:
This method is a bit bulky. An alternative method is to extend the 'String' class using 'prototype'
String.prototype.setCharAt = function(index,char) {
if(index > this.length-1) return str;
return this.substr(0,index) + char + this.substr(index+1);
}
//Demo
var str = 'Hello World';
str = str.setCharAt(4,',');
alert(str);
A rather complicated way to do a simple thing. Am I missing something? Is there an easier way to do this?

Comments
function setChars (s, at, c) {
return s.substr(0,at) + c.substr(0,s.length-at) + s.substr(at + c.length);
}
By the way, your fonction doesn't work : your variable 'char' is a reserved word ;-)
Take care,
Farben
return s.substr(0,at) + c.substr(0,s.length-at) + s.substr(at + c.length);
}
yours doesn't work either
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.