我有一个字符串,比如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 "完成"));

然后你可以调用函数:

其他回答

谢谢你的回答!

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

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

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

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

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

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

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