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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

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

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

其他回答

"hello world".replace(/(.{3})./, "$1h")
// 'helho world'

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

它更注重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()”/>

JavaScript中没有replacat函数。你可以使用下面的代码替换任意字符串中指定位置的任意字符:

函数 rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); 警报; } 函数集CharAt(str,index,chr) { if(索引 > str.length-1) 返回 str; 返回 str.substring(0,index) + chr + str.substring(index+1); } <button onclick=“rep();”>click</button>

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

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

可以使用以下函数替换字符串特定位置的字符或字符串。使用String.prototype.replaceAllMatches()函数替换以下所有匹配案例。

String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

测试:

var str = "yash yas $dfdas.**";

console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );

输出:

Index Matched replace :  yash yas $dfd*.**
Index Matched replace :  yash ~as $dfdas.**