EN
TypeScript - replace part of string from given index
0
points
In this article, we're going to have a look at how to replace part of a string from a given index in TypeScript.
Quick solution:
const text: string = 'This is text.';
const index: number = 2;
const insert: string = '__';
const result: string = text.substring(0, index) + insert + text.substring(index + insert.length);
console.log(result); // Th__ is text.
1. Custom method example
Presented in this section solution allows inserting text outside of given string filling space with any characters (by default with space).
const repeatText = (count: number, text: string): string => {
let result = '';
for (let i = 0; i < count; ++i) {
result += text;
}
return result;
};
const replaceText = (text: string, insert: string, index: number, spacer?: string): string => {
if (spacer == null) {
spacer = ' ';
}
const prefix = text.substring(0, index);
const postfix = text.substring(index + insert.length);
const space = repeatText(index - text.length, spacer);
return prefix + space + insert + postfix;
};
// Usage example:
console.log(replaceText('This is text.', '__', 0)); // __is is text.
console.log(replaceText('This is text.', '__', 2)); // Th__ is text.
console.log(replaceText('This is text.', '__', 11)); // This is tex__
console.log(replaceText('This is text.', '__', 13)); // This is text.__
console.log(replaceText('This is text.', '__', 15)); // This is text. __
console.log(replaceText('text...', '__', 10, '++')); // text...++++++__
Output:
__is is text.
Th__ is text.
This is tex__
This is text.__
This is text. __
text...++++++__
2. Custom method example with ES 2015
ES 2015 introduced repeat() method for string.
const replaceText = (text: string, insert: string, index: number, spacer: string = ' '): string => {
const prefix = text.substring(0, index);
const postfix = text.substring(index + insert.length);
const space = spacer.repeat(index < text.length ? 0 : index - text.length);
return prefix + space + insert + postfix;
};
// Usage example:
console.log(replaceText('This is text.', '__', 0)); // __is is text.
console.log(replaceText('This is text.', '__', 2)); // Th__ is text.
console.log(replaceText('This is text.', '__', 11)); // This is tex__
console.log(replaceText('This is text.', '__', 13)); // This is text.__
console.log(replaceText('This is text.', '__', 15)); // This is text. __
console.log(replaceText('text...', '__', 10, '++')); // text...++++++__
Output:
__is is text.
Th__ is text.
This is tex__
This is text.__
This is text. __
text...++++++__