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.

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

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/

1 Comment

This is how I would do it personally. ♥ regex.
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.

1 Comment

@cr0nicz I was referring to Underscore.string. Check the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.