How do I replace a character at a particular index

2018-12-31 03:09发布

I have a string, let's say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?

var str = "hello world";

I need something like

str.replaceAt(0,"h");

19条回答
高级女魔头
2楼-- · 2018-12-31 03:32

In Javascript strings are immutable so you have to do something like

var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);

To replace the character in x at i with 'h'

查看更多
泪湿衣
3楼-- · 2018-12-31 03:32

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

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

var s = "new function";
alert(s.insert(4,"insert string "));

Then you can call the function:

查看更多
旧时光的记忆
4楼-- · 2018-12-31 03:34

@CemKalyoncu: Thanks for the great answer!

I also adapted it slightly to make it more like the Array.splice method (and took @Ates' note into consideration):

spliceString=function(string, index, numToDelete, char) {
      return string.substr(0, index) + char + string.substr(index+numToDelete);
   }

var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"
查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 03:36

There are lot of answers here, and all of them are based on two methods:

  • METHOD1: split the string using two substrings and stuff the character between them
  • METHOD2: convert the string to character array, replace one array member and join it

Personally, I would use these two methods in different cases. Let me explain.

@FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.

@vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.

But what will happen if I have to make quite a few replacements?

I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:

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

I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).

Results:

  • TEST1: 195ms
  • TEST2: 6ms

It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???

What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.

So, it's all about choosing the right tool for the job. Again.

查看更多
唯独是你
6楼-- · 2018-12-31 03:38

In JavaScript, strings are immutable, which means the best you can do is create a new string with the changed content, and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

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

And use it like this:

var hello="Hello World";
alert(hello.replaceAt(2, "!!")); //should display He!!o World
查看更多
笑指拈花
7楼-- · 2018-12-31 03:39

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.

查看更多
登录 后发表回答