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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15441861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:46:52  来源:igfitidea点击:

How to replace characters by index in a JavaScript string?

javascripthtmlstringreplacesubstring

提问by vcapra1

If I have the string "hello" and I want to replace the second and third character with _, how can i do that, given only the location of the substring, not what it actually is.

如果我有字符串“hello”并且我想用 _ 替换第二个和第三个字符,我该怎么做,只给出子字符串的位置,而不是它的实际位置。

回答by MikeM

str = str.replace( /^(.)../, '__' );

The .matches any character except a newline.

.换行符以外的任何字符匹配。

The ^represents the start of the string.

^表示字符串的开始。

The ()captures the character matched by the first .so it can be referenced in the replacement string by $1.

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

Anything that matches the regular expression is replaced by the replacement string '$1__', so the first three characters at the start of the string are matched and replaced with whatever was matched by the first .plus __.

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

回答by jn_pdx

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

str.replaceAt(1,"_");
str.replaceAt(2,"_");

Taken from: How do I replace a character at a particular index in JavaScript?

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