Remove or Replace a Substring in JavaScript String

When the start and end indexes are known

If we know of the start and end index, we can remove or replace the substring from a JavaScript string in the following way:

1. Remove


const txt = `This is some text.

ABCDEDFGHI

Ths is the continutation of the text.
`;

const txtAfterRemoval = txt.slice(0, 20) + txt.slice(30);

console.log(txtAfterRemoval);

Here the substring to be removed is from index 20 till 30. We simply slice and concatenate the results:

This is some text.



Ths is the continutation of the text.

2. Replace

Using the same above method a substring can be replaced:

const txt = `This is some text.

ABCDEDFGHI

Ths is the continutation of the text.
`;

const txtAfterReplacement = txt.slice(0, 20) + "IJKLMNOPQRST" + txt.slice(30);

console.log(txtAfterReplacement);

And the result will be:

This is some text.

IJKLMNOPQRST

Ths is the continutation of the text.

See also

When you purchase through links on techighness.com, I may earn an affiliate commission.