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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

你可以试试

var strArr = str.split("");

strArr[0] = 'h';

str = strArr.join("");

查看打印步骤的函数

steps(3)
//       '#  '
//       '## '
//       '###'

function steps(n, i = 0, arr = Array(n).fill(' ').join('')) {
  if (i === n) {
    return;
  }

  str = arr.split('');
  str[i] = '#';
  str = str.join('');
  console.log(str);

  steps(n, (i = i + 1), str);
}

其他回答

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"

你可以扩展字符串类型来包含inset方法:

String.prototype.append =函数(索引,值){ 返回this.slice(0,index) + value + this.slice(index); }; var s = "新字符串"; 警报(s。追加(4 "完成"));

然后你可以调用函数:

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

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

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

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

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