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

然后你可以调用函数:

其他回答

如果你想替换字符串中的字符,你应该创建可变字符串。这些本质上是字符数组。你可以创建一个工厂:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

然后你可以访问字符,整个数组转换为字符串时使用的字符串:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"

我这样做是为了使字符串正确的大小写,也就是说,第一个字母是大写的,其余的都是小写的:

function toProperCase(someString){
    
    return someString.charAt(0).toUpperCase().concat(someString.toLowerCase().substring(1,someString.length));
    
};

首先要做的是确保所有的字符串都是小写的- someString.toLowerCase()

然后它将第一个字符转换为大写字符-someString.charAt(0)。

然后它取剩下的字符串减去第一个字符的子字符串-someString.toLowerCase().substring(1,someString.length))

然后它将两者连接起来并返回新的字符串-someString.charAt(0).toUpperCase().concat(someString.toLowerCase().substring(1,someString.length))

可以为替换字符索引和替换字符添加新的参数,然后形成两个子字符串,替换被索引的字符,然后以大致相同的方式连接。

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

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

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

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);
str = str.split('');
str[3] = 'h';
str = str.join('');