How to remove the first occurrence of a character from a string in JavaScript

1 Answer

0 votes
String.prototype.removeFirstCharacter = function(char) {
    const found = this.indexOf(char);
    
    if (found !== -1) {
        return this.slice(0, found) + this.slice(found + 1);
    }
    
    return this;
}


let str = 'c++ c javascript python javascript php';

const char = 'j';

str = str.removeFirstCharacter(char);

console.log(str);
  
  
  
  
  
/*
run:
  
"c++ c avascript python javascript php"
  
*/

 



answered Apr 16, 2022 by avibootz
...