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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

使用字符串的一行程序。替换回调(不支持表情符号):

// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"

解释道:

//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
   if (index == 0) //we want to replace the first character
     return 'f'
   return character //leaving other characters the same
})

其他回答

使用扩展语法,你可以将字符串转换为数组,在给定位置分配字符,然后转换回字符串:

Const STR = "hello world"; 函数replace (s, i, c) { Const arr =[…s];//将字符串转换为数组 Arr [i] = c;//在pos i处设置字符c 返回arr.join(”);//返回字符串 } //打印"hallo world" console.log(replace (str, 1, 'a'));

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"
str = str.split('');
str[3] = 'h';
str = str.join('');

你可以试试

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

与vector打交道通常最有效的方法是接触String。

我建议使用以下函数:

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    a[index] = char;
    return a.join("");
}

运行这段代码:

String.prototype.replaceAt=function(index, char) { var a = this.split(“”); a[索引] = 字符; 返回 a.join(“”); } var str = “hello world”; str = str.replaceAt(3, “#”); document.write(str);