placeAtJavaScript中没有功能。您可以使用以下代码来替换指定位置上的任何字符串中的任何字符:
function Rep() {
var str = 'Hello World';
str = setCharAt(str,4,'a');
alert(str);
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
<button onclick="Rep();">click</button>
在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