Javascript在索引处替换字符问题

javascript replace character at index problem

本文关键字:字符 问题 替换 索引 Javascript      更新时间:2023-09-26

我让我的replaceAt方法看起来像这里的东西

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

我有一个trim at函数,它从字符串的特定索引处删除空白,看起来像这样:

String.prototype.startTrimAt = function(i) {
    var string = this;
    while (string.charAt(i) == ' '){
        string = string.replaceAt(i, '');
    }
    return string;
};

这个函数是这样的:

"(  tree)".startTrimAt(1); //returns (tree)

我遇到的问题是,它只是在startTrimAt函数循环,我不知道为什么。任何帮助将不胜感激。由于

replaceAt()方法似乎不适合空字符串。

String.prototype.replaceAt = function(index, c) {
    return this.substr(0, index) + c + this.substr(index + (c.length == 0 ? 1 : c.length));
}

当第二个参数为零长度字符串时,您的replaceAt无法正常工作:

"( tree)".replaceAt(1,'')//returns "(  tree)"

请记住,您在第二个参数中替换了与字符串相同数量的字符。当该字符串的长度为0时,将替换0个字符。

由于字符串实际上没有改变,字符1总是' ',因此是无限循环。

注意

"( tree)".substr(0,1) //returns "("

"( tree)".substr(1,6) //returns " tree)"

您的replaceAt方法不起作用。空字符串''的长度是0,所以它返回substr(0, 1)substr(1),这相当于原始字符串( tree),因此循环。因为你只给出了一个索引参数,我假设你只替换了一个字符,所以你的replaceAt方法应该是:

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

一次删除一个字符是低效的。您可以使用正则表达式一次替换所有空格。

String.prototype.startTrimAt = function(i) {
    return this.substr(0,i) + this.substr(i).replace(/^ +/, '');
};

或:

String.prototype.startTrimAt = function(i) {
    var re = new RegExp('^(.{'+i+'}) +');
    return this.replace(re, '$1');
};