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

kql*_*ert 32 javascript jquery

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

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

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

我怎么能这样做?

Vis*_*ioN 61

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

String.prototype.replaceBetween = function(start, end, what) {
  return this.substring(0, start) + what + this.substring(end);
};

console.log("The Hello World Code!".replaceBetween(4, 9, "Hi"));
Run Code Online (Sandbox Code Playgroud)

  • @Exception参考什么?函数引用很便宜,只会创建一个.该函数不会被克隆,甚至不会被引用.我不认为扩展`String.prototype`会导致在javascript引擎内部创建非原始String对象. (3认同)

Rob*_*uch 11

接受的答案是正确的,但我想避免扩展 String prototype

function replaceBetween(origin, startIndex, endIndex, insertion) {
  return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}
Run Code Online (Sandbox Code Playgroud)

用法:

replaceBetween('Hi World', 3, 7, 'People');

// Hi People
Run Code Online (Sandbox Code Playgroud)

如果使用简洁的箭头函数,那么它是:

const replaceBetween = (origin, startIndex, endIndex, insertion) =>
  origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
Run Code Online (Sandbox Code Playgroud)

如果使用模板文字,则为:

const replaceBetween = (origin, startIndex, endIndex, insertion) =>
  `${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;
Run Code Online (Sandbox Code Playgroud)


Bla*_*ger 7

Array.spliceJavaScript中有一种方法可以完成这项工作,但是没有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('');
Run Code Online (Sandbox Code Playgroud)

  • 请注意,虽然可以在字符串上调用`Array.splice`,但它不会按预期运行,因为字符串是不可变的. (3认同)
  • 我理解这篇文章已经有一段时间了.目前`split`和`join`与许多表情符号(例如)不兼容 (2认同)