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);

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

Farben at 03 Jun, 2007 12:16
To change one char or more, without affecting the original string length :

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
Reply to this.
Anonymous at 08 Apr, 2008 09:22
function setChars (s, at, c) {
return s.substr(0,at) + c.substr(0,s.length-at) + s.substr(at + c.length);
}
yours doesn't work either
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.