Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
halfacreyum Avatar asked Nov 21 '16 00:11

halfacreyum


Video Answer


2 Answers

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 that uses substr instead of substring. The difference between substr and substring is in the second parameter, for substring is the index to stop and for substr the length to return. You can 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"
like image 195
Christos Lytras Avatar answered Oct 29 '22 17:10

Christos Lytras


The easiest way is to just slice the front part and the back part and splice them back together:

var string = "I am a string";
string = string.substring(0, 7) + string.substring(10);
console.log(string);
// => I am a ing
like image 29
Amadan Avatar answered Oct 29 '22 15:10

Amadan