2012-12-18 106 views
5

如何替換給定起始位置和長度的字符串的子串?用JavaScript中的範圍替換字符串中的子串

我希望這樣的事情:

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

使string就等於

"this is a replacement string" 

..但我找不到這樣的事情。

任何幫助表示讚賞。

回答

7

像這樣:

var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length); 

你可以把它添加到字符串的原型:

String.prototype.splice = function(start,length,replacement) { 
    return this.substr(0,start)+replacement+this.substr(start+length); 
} 

(我稱之爲splice,因爲它是非常相似的同名陣列功能)

+0

我看到你的方法也愚蠢dv'ed':/' – VisioN

2

Short RegExp版本:

str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word); 

實施例:

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/

+2

這就是我將如何親自做。 ♥正則表達式。 – elclanrs

+1

正則表達式不必要的緩慢:http://jsperf.com/string-splice –

0

Underscore String library具有按照指定哪個工作原理完全剪接方法。

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

圖書館還有很多其他有用的功能。它的時鐘爲8kb,可在cdnjs上找到。

+0

@ cr0nicz我指的是Underscore.string。檢查鏈接。 – tghw

0

對於它的價值,此函數將基於兩個索引而不是第一個索引和長度進行替換。

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