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:
xxxxxxxxxx
1
const text: string = 'This is text.';
2
const index: number = 2;
3
const insert: string = '__';
4
5
const result: string = text.substring(0, index) + insert + text.substring(index + insert.length);
6
7
console.log(result); // Th__ is text.
Presented in this section solution allows inserting text outside of given string filling space with any characters (by default with space).
xxxxxxxxxx
1
const repeatText = (count: number, text: string): string => {
2
let result = '';
3
for (let i = 0; i < count; ++i) {
4
result += text;
5
}
6
return result;
7
};
8
9
const replaceText = (text: string, insert: string, index: number, spacer?: string): string => {
10
if (spacer == null) {
11
spacer = ' ';
12
}
13
const prefix = text.substring(0, index);
14
const postfix = text.substring(index + insert.length);
15
const space = repeatText(index - text.length, spacer);
16
17
return prefix + space + insert + postfix;
18
};
19
20
21
// Usage example:
22
23
console.log(replaceText('This is text.', '__', 0)); // __is is text.
24
console.log(replaceText('This is text.', '__', 2)); // Th__ is text.
25
console.log(replaceText('This is text.', '__', 11)); // This is tex__
26
27
console.log(replaceText('This is text.', '__', 13)); // This is text.__
28
console.log(replaceText('This is text.', '__', 15)); // This is text. __
29
30
console.log(replaceText('text...', '__', 10, '++')); // text...++++++__
Output:
xxxxxxxxxx
1
__is is text.
2
Th__ is text.
3
This is tex__
4
This is text.__
5
This is text. __
6
text...++++++__
ES 2015 introduced repeat()
method for string.
xxxxxxxxxx
1
const replaceText = (text: string, insert: string, index: number, spacer: string = ' '): string => {
2
const prefix = text.substring(0, index);
3
const postfix = text.substring(index + insert.length);
4
const space = spacer.repeat(index < text.length ? 0 : index - text.length);
5
6
return prefix + space + insert + postfix;
7
};
8
9
10
// Usage example:
11
12
console.log(replaceText('This is text.', '__', 0)); // __is is text.
13
console.log(replaceText('This is text.', '__', 2)); // Th__ is text.
14
console.log(replaceText('This is text.', '__', 11)); // This is tex__
15
16
console.log(replaceText('This is text.', '__', 13)); // This is text.__
17
console.log(replaceText('This is text.', '__', 15)); // This is text. __
18
19
console.log(replaceText('text...', '__', 10, '++')); // text...++++++__
Output:
xxxxxxxxxx
1
__is is text.
2
Th__ is text.
3
This is tex__
4
This is text.__
5
This is text. __
6
text...++++++__