从字符串对象中删除第一次出现的字母

Remove first occurrence of a letter from a string object

我正在尝试为一个项目扩展 javascript 字符串功能,我希望能够有一个函数来删除第一次出现的字符串。
JS 不允许使用字符串函数更改文本。
我认为错误是试图将文本分配给 'this'。
请帮助让我知道是否有其他方法可以实现此目的。 谢谢

// remove first occurrence of a letter from a string
String.prototype.removeFirstMatch = function(char){
 var text = '';
 for(i = 0; i < this.length; i++){
  if(this[i] == char){
   text = this.slice(0, i) + this.slice(i + 1, this.length);
  }
 }
 this = text;
}

var word = 'apple';

word.removeFirstMatch('p');

console.log(word);

Javascript 中的字符串是不可变的。这意味着您不能更改字符串对象的内容。所以,像 .slice() 这样的东西实际上并没有修改字符串,它 return 是一个新字符串。

因此,您的 .removeFirstMatch() 方法需要 return 一个新字符串,因为它无法修改当前字符串对象。

您也不能分配给 Javascript 中的 this

这是一个 return 新字符串的版本:

// remove first occurrence of a letter from a string
String.prototype.removeFirstMatch = function(char) {
    for (var i = 0; i < this.length; i++) {
        if (this.charAt(i) == char) {
            return this.slice(0, i) + this.slice(i + 1, this.length);
        }
    }
    return this;
}

var word = 'apple';
var newWord = word.removeFirstMatch('p');
document.write(newWord);

注意:如果i我也把var放在前面,使它成为局部变量而不是隐式全局变量,并允许它在strict中运行模式。而且,我 return 在找到第一个匹配项后立即退出 for 循环,而不是继续循环。而且,它 return 是新字符串,或者如果没有进行任何更改,它 return 是原始字符串。


这可以稍微清理一下:

// remove first occurrence of a letter from a string
String.prototype.removeFirstMatch = function(char) {
    var found = this.indexOf(char);
    if (found !== -1) {
        return this.slice(0, found) + this.slice(found + 1);
    }
    return this;
}

var word = 'apple';
var newWord = word.removeFirstMatch('p');
document.write(newWord);

javascript 中的字符串是不可变的(您无法更改字符串...但您可以重新分配字符串...)

此外,您不能在函数内更改 this 的值。请参阅@TobiasCohen 的回答 here

但是,您可以 return 更新值,然后将 word 重新分配给 returned 值...

String.prototype.removeFirstMatch = function(char){
  var text = '';
  for(i = 0; i < this.length; i++){
    if(this[i] == char){
        text = this.slice(0, i) + this.slice(i + 1, this.length);
    }
  }
  return text;
}
var word = 'apple';
word = word.removeFirstMatch('p');
console.log(word);

字符串是不可变的(您不能修改字符串)。但是你可以这样做:

String.prototype.removeFirstMatch = function(char){
var text = '';
for(i = 0; i < this.length; i++){
  if(this[i] == char){
    text = this.slice(0, i) + this.slice(i + 1, this.length);
  }
}
return text;
}
 var word = 'apple';
 newWord = word.removeFirstMatch('p');
 console.log(newWord);