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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

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

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

然后你可以调用函数:

其他回答

这里的方法很复杂。 我会这样做:

var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");

这很简单。

下面是我使用三元和映射操作符的解决方案。如果你问我,我觉得可读性更强,更易维护,更容易理解。

它更注重es6和最佳实践。

函数替换At() { const replaceAt = document.getElementById('replaceAt').value; const str = 'ThisIsATestStringToReplaceCharAtSomePosition'; const newStr = Array.from(str).map((character, charIndex) => charIndex === (replaceAt - 1) ?'' : 字符).join(''); console.log('New string: ${newStr}'); } <input type=“number” id=“replaceAt” min=“1” max=“44” oninput=“replaceAt()”/>

我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"

    var validate = function(value){
        var notAllowed = [";","_",">","<","'","%","$","&","/","|",":","=","*"];
        for(var i=0; i<value.length; i++){
            if(notAllowed.indexOf(value.charAt(i)) > -1){
               value = value.replace(value.charAt(i), "");
               value = validate(value);
            }
       }
      return value;
   }
str = str.split('');
str[3] = 'h';
str = str.join('');

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

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

然后你可以调用函数: