如何在JavaScript中替换特定索引处的字符?
问题描述:
我有一个字符串,让我们说 Hello world
我需要替换索引3处的char。如何通过指定索引来替换char?
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";
我需要类似
str.replaceAt(0,"h");
答
在JavaScript中,字符串是不可变的,这意味着您可以做的最好的事情是创建一个包含更改内容的新字符串,并指定变量指向它。
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.
您需要定义你自己的 replaceAt()
函数:
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);
}
并按如下方式使用:
var hello="Hello World";
alert(hello.replaceAt(2, "!!")); //should display He!!o World