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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

您可以使用子字符串函数在目标索引之前和目标索引之后首先选择文本,然后与您潜在的字符或字符串进行连接。这个更好

const myString = "Hello world";
const index = 3;
const stringBeforeIndex = myString.substring(0, index);
const stringAfterIndex = myString.substring(index + 1);
const replaceChar = "X";
myString = stringBeforeIndex + replaceChar + stringAfterIndex;
console.log("New string - ", myString)

or

const myString = "Hello world";
let index = 3;
myString =  myString.substring(0, index) + "X" + myString.substring(index + 1);

其他回答

这类似于Array.splice:

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

这很容易用RegExp实现!

const str = 'Hello RegEx!';
const index = 11;
const replaceWith = 'p';

//'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);

//< "Hello RegExp"
"hello world".replace(/(.{3})./, "$1h")
// 'helho world'

概括Afanasii Kurakin的回答,我们有:

函数替换(str, index, ch) { 返回str.replace(/。/g, (c, i) => i == index ?Ch: c); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World

让我们展开并解释正则表达式和replace函数:

函数replace (str, index, newChar) { 函数替换符(origChar, strIndex) { if (strIndex === index) 返回newChar; 其他的 返回origChar; } 返回str.replace(/。/ g,替代者); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World

正则表达式。恰好匹配一个字符。g使它匹配for循环中的每个字符。给定原始字符和该字符在字符串中位置的下标,将调用replacement函数。我们用一个简单的if语句来决定返回的是origChar还是newChar。

假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。

var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");