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,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + 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(
chr
) 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,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + 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?
blog comments powered by Disqus