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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

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

其他回答

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

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

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

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);

function dothis() { var x = document.getElementById("x").value; var index = document.getElementById("index").value; var text = document.getElementById("text").value; var length = document.getElementById("length").value; var arr = x.split(""); arr.splice(index, length, text); var result = arr.join(""); document.getElementById('output').innerHTML = result; console.log(result); } dothis(); <input id="x" type="text" value="White Dog" placeholder="Enter Text" /> <input id="index" type="number" min="0"value="6" style="width:50px" placeholder="index" /> <input id="length" type="number" min="0"value="1" style="width:50px" placeholder="length" /> <input id="text" type="text" value="F" placeholder="New character" /> <br> <button id="submit" onclick="dothis()">Run</button> <p id="output"></p>

此方法适用于较小长度的字符串,但对于较大的文本可能很慢。

var x = "White Dog";
var arr = x.split(""); // ["W", "h", "i", "t", "e", " ", "D", "o", "g"]
arr.splice(6, 1, 'F');

/* 
  Here 6 is starting index and 1 is no. of array elements to remove and 
  final argument 'F' is the new character to be inserted. 
*/
var result = arr.join(""); // "White Fog"

var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);

你可以试试

var strArr = str.split("");

strArr[0] = 'h';

str = strArr.join("");