How to destroy characters from two points in a string?

I would like to delete characters destructively from two points in a string, so when a string is called after deletion, it will not contain deleted characters.

Example

var string = "I am a string";

I would like to: delete (0, 7);

When I call the string again, it should return:

console.log (string) => string

Example 2

var string = "I am a string";

I would like to: delete (7, 10);

When I call the string again, it should return:

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

+5
source share
2 answers

See javascript substring .

In your example, use this:

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

OUTPUTS

 string 

UPDATE

To remove part of a string, you can do this by executing the first characters you want with the last characters you want, for example:

 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 to remove parts of strings, see Ken White's answer , which uses substr instead of substring . The difference between substr and substring is in the second parameter, for substring - the stop index, 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 as (7, 10) , then you 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" 
+4
source

The easiest way is to simply slice the front and back and combine them together:

 var string = "I am a string"; string = string.substring(0, 7) + string.substring(10); console.log(string); // => I am a ing 
+1
source

Source: https://habr.com/ru/post/1260054/


All Articles