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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

如果你想替换字符串中的字符,你应该创建可变字符串。这些本质上是字符数组。你可以创建一个工厂:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

然后你可以访问字符,整个数组转换为字符串时使用的字符串:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"

其他回答

你可以试试

var strArr = str.split("");

strArr[0] = 'h';

str = strArr.join("");

我用负下标的安全方法

/**
 * @param {string} str 
 * @param {number} index 
 * @param {string} replacement 
 * @returns {string}
 */
static replaceAt (str, index, replacement)
{
    if (index < 0) index = str.length + index
    if (index < 0 || index >= str.length) throw new Error(`Index (${index}) out of bounds "${str}"`)
    return str.substring(0, index) + replacement + str.substring(index + 1)
}

像这样使用它:

replaceAt('my string', -1, 'G') // 'my strinG'
replaceAt('my string', 2, 'yy') // 'myyystring'
replaceAt('my string', 22, 'yy') // Uncaught Error: Index (22) out of bounds "my string"

这很容易用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"

谢谢你的回答!

我还稍微调整了它,使它更像数组。拼接方法(并考虑了@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处的字符