如何替换两个索引之间的子字符串

我想在Javascript中的两个索引之间替换文本,例如:

str = "The Hello World Code!"; str.replaceBetween(4,9,"Hi"); // outputs "The Hi World Code" 

索引和字符串都是动态的。

我怎么能这样做?

JavaScript中没有这样的方法。 但是你可以随时创建自己的:

 String.prototype.replaceBetween = function(start, end, what) { return this.substring(0, start) + what + this.substring(end); }; "The Hello World Code!".replaceBetween(4, 9, "Hi"); // >> "The Hi World Code!" 

JavaScript中有一个Array.splice方法可以完成这项工作,但没有String.splice 。 但是,如果将字符串转换为数组,则:

 var str = "The Hello World Code!"; var arr = str.split(''); var removed = arr.splice(4,5,"Hi"); // arr is modified str = arr.join(''); 

当你需要完全替换特定索引处的字符串时,另一种方法是使用与String.prototype.replace完全相同的函数调用可能是这样的:

 String.prototype.replaceAt = function(index, fromString, toString) { let hasWrongParams = typeof index !== 'number' || !fromString || typeof fromString !== 'string' || !toString || typeof toString !== 'string'; if(hasWrongParams) return ''; let fromIndex = index; let toIndex = index + fromString.length; return this.substr(0, fromIndex) + toString + this.substr(toIndex); } 

https://gist.github.com/kwnccc/9df8554474e39f4b17a07efbbdf7971c

例如:

 let string = 'This is amazing world, it's still amazing!'; string.replaceAt(8, 'amazing', 'worderful'); // 'This is worderful world, it's still amazing!' string.replaceAt(34, 'amazing', 'worderful'); // 'This is amazing world, it's still worderful!' 

这就是它对我有用的方式。

 var str = "The Hello World Code!"; var newStr="Hi" var startIndex= 4; // start index of 'H' from 'Hello' var endIndex= 8; // end index of 'o' from 'Hello' var preStr = str.substring(0, startIndex); var postStr = str.substring(endIndex+1, str.length - 1); var result = preStr+newStr+postStr;); // outputs "The Hi World Code" 

小提琴: http : //jsfiddle.net/ujvus6po/1/