最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Replace substring in string with range in JavaScript - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Apr 30, 2020 at 1:36 bb216b3acfd8f72cbc8f899d4d6963 76111 silver badges21 bronze badges asked Dec 18, 2012 at 1:44 Jack GreenhillJack Greenhill 10.5k12 gold badges41 silver badges70 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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)

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/

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.

发布评论

评论列表(0)

  1. 暂无评论