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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

你不能。取位置前后的字符并连接成一个新字符串:

var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);

其他回答

你不能。取位置前后的字符并连接成一个新字符串:

var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);

谢谢你的回答!

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

解决方案不工作的负索引,所以我添加了一个补丁。

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
    
}

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"