开发者

javascript replace character at index problem

I have my replaceAt method look like something from here

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

I have a trim at function which removes whitespace starting at a 开发者_C百科specific index from a string that looks like this:

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

So this function would work like this:

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

The problem i am having is that it just loops in the startTrimAt function and I am not sure why. Any help would be appricated. Thanks


The replaceAt() method doesn't seem right for empty string.

Try

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


Your replaceAt does not work as you expect when the second argument is a zero-length string:

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

Remember, you're replacing the same number of characters as the string in your second argument. When that string has length zero, you replace zero characters.

Since the string isn't actually altered, character 1 is always ' ', hence your infinite loop.

Note that

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

and

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


You're replaceAt method doesn't work well. The length of the empty string '' is 0, so it's returning substr(0, 1) and substr(1) which is equivalent to the original string ( tree) hence the loop. Since you're giving a single index parameter I assume you're only ever replacing a single character, so your replaceAt method should be:

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


Removing one character at a time is inefficient. You can make use of regexes to replace all spaces at once.

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

Or:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜