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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

在JavaScript中,字符串是不可变的,这意味着您所能做的最好的事情就是用更改后的内容创建一个新的字符串,并将变量赋值指向它。

你需要自己定义replace()函数:

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

像这样使用它:

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

其他回答

下面是我使用三元和映射操作符的解决方案。如果你问我,我觉得可读性更强,更易维护,更容易理解。

它更注重es6和最佳实践。

函数替换At() { const replaceAt = document.getElementById('replaceAt').value; const str = 'ThisIsATestStringToReplaceCharAtSomePosition'; const newStr = Array.from(str).map((character, charIndex) => charIndex === (replaceAt - 1) ?'' : 字符).join(''); console.log('New string: ${newStr}'); } <input type=“number” id=“replaceAt” min=“1” max=“44” oninput=“replaceAt()”/>

这里的方法很复杂。 我会这样做:

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

这很简单。

你不能。取位置前后的字符并连接成一个新字符串:

var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);

JavaScript中没有replacat函数。你可以使用下面的代码替换任意字符串中指定位置的任意字符:

函数 rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); 警报; } 函数集CharAt(str,index,chr) { if(索引 > str.length-1) 返回 str; 返回 str.substring(0,index) + chr + str.substring(index+1); } <button onclick=“rep();”>click</button>

在JavaScript中,字符串是不可变的,这意味着您所能做的最好的事情就是用更改后的内容创建一个新的字符串,并将变量赋值指向它。

你需要自己定义replace()函数:

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

像这样使用它:

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