Is there a method to remove a substring from a string?

Asked

Viewed 110 times

1

For now I use the replace method for this but wanted to know if there is a method that exclusive to do this:

pontos = `${parseInt(pontos) + aposta}${pontos.replace(parseInt(pontos), "")}`;
  • What exactly do you need to do? And why the method replace does not meet your needs? You want to make a replace and believes that the method replace Isn’t that what you need? So it’s not a little clear what you want.

  • i just want to remove one substring from inside another and replace works but I don’t know if it’s the best.

  • He’s the best. He was created for this.

  • the function replace() won’t help you there ? @Moraisvilson

1 answer

3


It doesn’t exist, but you can make one. Just add to the prototype type String that all strings, both existing and those still to be instantiated, will have.

String.prototype.remover = function (input) {   
    var output = this;
    while (output.indexOf(input) > -1) { // só porque o replace não é global.
        output = output.replace(input, "");
    }
    return output;
}

Note that this method does not change the string, but returns a new one.

And to test, after running the code above, you can do it on the console:

"abcde".remover("c");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.