Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从字符串对象中删除字母的第一个匹配项_Javascript_Javascript Objects - Fatal编程技术网

Javascript 从字符串对象中删除字母的第一个匹配项

Javascript 从字符串对象中删除字母的第一个匹配项,javascript,javascript-objects,Javascript,Javascript Objects,我正在尝试为一个项目扩展javascript字符串功能,我希望能够有一个函数通过一个函数删除字符串的第一次出现。 JS不允许使用字符串函数更改文本。 我认为错误是试图将文本分配给“this”。 请告诉我是否有其他方法来实现这一点。 谢谢 //删除字符串中第一个出现的字母 String.prototype.removeFirstMatch=函数(字符){ var text=''; 对于(i=0;i

我正在尝试为一个项目扩展javascript字符串功能,我希望能够有一个函数通过一个函数删除字符串的第一次出现。
JS不允许使用字符串函数更改文本。
我认为错误是试图将文本分配给“this”。
请告诉我是否有其他方法来实现这一点。 谢谢

//删除字符串中第一个出现的字母
String.prototype.removeFirstMatch=函数(字符){
var text='';
对于(i=0;iconsole.log(word)Javascript中的字符串是不可变的。这意味着您不能更改字符串对象的内容。因此,类似于
.slice()
的内容实际上并没有修改字符串,而是返回一个新字符串

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

在Javascript中,您也不能将
分配给该

以下是返回新字符串的版本:

//删除字符串中第一个出现的字母
String.prototype.removeFirstMatch=函数(字符){
for(var i=0;i文件。书写(newWord)javascript中的字符串是不可变的(您不能更改字符串…但可以重新分配字符串…)

此外,您不能在函数中更改
this
的值。见@TobiasCohen的答案

但是,您可以返回更新后的值,然后将
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';
word = word.removeFirstMatch('p');
console.log(word);
String.prototype.removeFirstMatch=函数(char){
var text='';
对于(i=0;i
字符串是不可变的(不能修改字符串)。但是,您可以这样做:

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);
String.prototype.removeFirstMatch=函数(char){
var text='';
对于(i=0;i