7

How can I replace a substring of a string given the starting position and the length?

I was hoping for something like this:

var string = "This is a test string";
string.replace(10, 4, "replacement");

so that string would equal

"this is a replacement string"

..but I can't find anything like that.

Any help appreciated.

Jack Greenhill
  • 10,240
  • 12
  • 38
  • 70

4 Answers4

9

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)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

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;
}
Austin Dean
  • 384
  • 3
  • 13
2

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/

VisioN
  • 143,310
  • 32
  • 282
  • 281
0

The Underscore String library has a splice method which works exactly as you specified.

_("This is a test string").splice(10, 4, 'replacement');
=> "This is a replacement string"

There are a lot of other useful functions in the library as well. It clocks in at 8kb and is available on cdnjs.

tghw
  • 25,208
  • 13
  • 70
  • 96