Replace substring in string with range in JavaScript

Like this:

var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length);

You can add it to the string's prototype:

String.prototype.splice = function(start,length,replacement) {
    return this.substr(0,start)+replacement+this.substr(start+length);
}

(I call this splice because it is very similar to the Array function of the same name)


For what it's worth, this function will replace based on two indices instead of first index and length.

splice: function(specimen, start, end, replacement) {
    // string to modify, start index, end index, and what to replace that selection with

    var head = specimen.substring(0,start);
    var body = specimen.substring(start, end + 1); // +1 to include last character
    var tail = specimen.substring(end + 1, specimen.length);

    var result = head + replacement + tail;

    return result;
}

Short RegExp version:

str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word);

Example:

String.prototype.sreplace = function(start, length, word) {
    return this.replace(
        new RegExp("^(.{" + start + "}).{" + length + "}"),
        "$1" + word);
};

"This is a test string".sreplace(10, 4, "replacement");
// "This is a replacement string"

DEMO: http://jsfiddle.net/9zP7D/