如何在JavaScript中的特定索引处替换字符?

JavaScript

JinJinPro

2020-03-12

我有一个字符串,假设Hello world我需要替换索引3处的char。如何通过指定索引来替换char?

var str = "hello world";

我需要类似的东西

str.replaceAt(0,"h");

第1109篇《如何在JavaScript中的特定索引处替换字符?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
猴子古一蛋蛋 2020.03.12

The methods on here are complicated. I would do it this way:

var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");

This is as simple as it gets.

GilGreen 2020.03.12

I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);

}
伽罗Tom猪猪 2020.03.12

If you want to replace characters in string, you should create mutable strings. These are essentially character arrays. You could create a factory:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

Then you can access the characters and the whole array converts to string when used as string:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"
Itachi理查德 2020.03.12

You can extend the string type to include the inset method:

String.prototype.append = function (index,value) {
  return this.slice(0,index) + value + this.slice(index);
};

var s = "New string";
alert(s.append(4,"complete "));

Then you can call the function:

Harry小小 2020.03.12

这里有很多答案,并且所有答案都基于两种方法:

  • 方法1:使用两个子字符串拆分字符串,并将字符填充在它们之间
  • 方法2:将字符串转换为字符数组,替换一个数组成员并将其加入

我个人将在不同情况下使用这两种方法。让我解释。

@FabioPhms:您的方法是我最初使用的方法,我担心它对包含许多字符的字符串不利。但是,问题是有多少个字符?我在10个“ lorem ipsum”段落中对其进行了测试,并花费了几毫秒的时间。然后我在大10倍的弦上进行了测试-确实没有太大的区别。

@ vsync,@ Cory Mawhorter:您的评论是明确的;但是,什么是大字符串呢?我同意对于32 ... 100kb的性能应该更好,并且应该对这一字符替换操作使用substring-variant。

但是,如果我不得不进行很多替换,将会发生什么?

我需要执行自己的测试以证明在这种情况下更快。假设我们有一种算法,可以处理由1000个字符组成的较短字符串。我们预计该字符串中的每个字符平均将被替换100次左右。因此,用于测试类似代码的代码是:

var str = "... {A LARGE STRING HERE} ...";

for(var i=0; i<100000; i++)
{
  var n = '' + Math.floor(Math.random() * 10);
  var p = Math.floor(Math.random() * 1000);
  // replace character *n* on position *p*
}

我为此制造了一个小提琴,就在这里有两个测试,TEST1(子字符串)和TEST2(数组转换)。

结果:

  • TEST1:195ms
  • TEST2:6ms

数组转换似乎比子字符串高2个数量级!所以-这里到底发生了什么?

实际发生的情况是,TEST2中的所有操作都是使用数组之类的赋值表达式在数组本身上完成的strarr2[p] = n与大字符串上的子字符串相比,分配确实非常快,而且很明显,它会赢。

因此,这全都在于为工作选择合适的工具。再次。

Tony樱番长 2020.03.12

This works similar to Array.splice:

String.prototype.splice = function (i, j, str) {
    return this.substr(0, i) + str + this.substr(j, this.length);
};
小宇宙 2020.03.12

使用向量通常最有效地联系String。

我建议以下功能:

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    a[index] = char;
    return a.join("");
}

运行以下代码段:

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    a[index] = char;
    return a.join("");
}

var str = "hello world";
str = str.replaceAt(3, "#");

document.write(str);

.... 2020.03.12

在JavaScript中,字符串是不可变的,这意味着您可以做的最好的事情是创建一个具有更改内容的新字符串,然后将变量分配为指向它。

您需要自己定义replaceAt()函数:

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

并像这样使用它:

var hello="Hello World";
alert(hello.replaceAt(2, "!!")); //should display He!!o World

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android