halfacreyum halfacreyum - 15 days ago 7
HTML Question

How to destructively remove characters from two points in a string?

I would like to remove the characters destructively from two points in a string, so when the string is called after the removal it would not include the removed characters.

Example



var string = "I am a string";

I'd like to: remove (0, 7);

When I call string again it should return:

console.log(string) => string

Example-2



var string = "I am a string";

I'd like to: remove (7, 10);

When I call string again it should return:

console.log(string) => I am a ing

Answer

See javascript substring.

For your example use this:

var string = "I am a string";
console.log(string.substring(7));

OUTPUTS

string

UPDATE

For removing a portionof a string, you can do it by concating the first wanted characters with the last wanted characters, something like this:

var string = "I am a string";
console.log(string.substr(0, 5) + string.substr(7));

OUTPUTS

I am string

If you want to have a direct function for removing portions of strings, see Ken White's answer and use something like this:

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

string.replaceAt(5, 2); // Outputs: "I am string"

Or if you want to use start and end like (7, 10), then have a function like this:

String.prototype.removeAt = function(start, end) {
  return this.substr(0, start) + this.substr(end);
}

string.removeAt(7, 10); // Outputs: "I am a ing"