如何在JavaScript字符串中用索引替换字符?

vca*_*ra1 -1 html javascript string replace substring

如果我有字符串"hello"并且我想用_替换第二个和第三个字符,我怎么能这样做,只给出子字符串的位置,而不是它实际上是什么.

Mik*_*keM 8

str = str.replace( /^(.)../, '$1__' );
Run Code Online (Sandbox Code Playgroud)

.场比赛除了换行符的任何字符.

^表示字符串的开始.

()字符的第一个匹配的捕获.,因此它可以通过替换字符串中引用$1.

与正则表达式匹配的任何内容都将替换为替换字符串'$1__',因此字符串开头的前三个字符将匹配并替换为第一个.加号匹配的任何字符__.


jn_*_*pdx 5

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

str.replaceAt(1,"_");
str.replaceAt(2,"_");
Run Code Online (Sandbox Code Playgroud)

摘自:如何在JavaScript中替换特定索引处的字符?