问题
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.
回答1:
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)
回答2:
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;
}
回答3:
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/
回答4:
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.
来源:https://stackoverflow.com/questions/13925103/replace-substring-in-string-with-range-in-javascript