Documentation and Books

Recent site activity

Web Development‎ > ‎JavaScript‎ > ‎

How to replace a single character at a known position in a String?

The following is a very nice solution to replace a single character at a known position in a String, it uses the prototype functionality to add a method replaceCharAt to the String class:

  <script type=text/javascript>

String.prototype.replaceCharAt=replaceCharAt;

function replaceCharAt(character, position) {
var result = new RegExp('^(.{'+ --position +'}).(.*)$','');
return this.replace(result,'$1'+character+'$2');
}
</script>

You can use this new function in the following way:

  <script type=text/javascript>

var text = "This is some text";
alert(text.replaceCharAt('H', 4));

</script>