Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace substring in string with range in JavaScript

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.

like image 344
Jack Greenhill Avatar asked Dec 18 '12 01:12

Jack Greenhill


1 Answers

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)

like image 159
Niet the Dark Absol Avatar answered Sep 19 '22 08:09

Niet the Dark Absol