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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

概括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。

其他回答

谢谢你的回答!

我还稍微调整了它,使它更像数组。拼接方法(并考虑了@Ates的笔记):

spliceString=function(string, index, numToDelete, char) {
      return string.substr(0, index) + char + string.substr(index+numToDelete);
   }

var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"

在Javascript中,字符串是不可变的,所以你必须这样做

var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);

用'h'替换x在i处的字符

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

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

你可以试试

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

这类似于Array.splice:

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