EN
JavaScript - replace part of string from given index
2 points
In this article, we're going to have a look at how to replace part of a string from a given index in JavaScript.
Quick solution:
xxxxxxxxxx
1
var text = 'This is text.'
2
var index = 2;
3
var insert = '__';
4
5
var result = text.substring(0, index) + insert + text.substring(index + insert.length);
6
7
console.log(result);
Note: read this article to know how to remove part of text for given indexes.
Check the below example for a better solution.
Presented in this section solution allows inserting text outside of given string filling space with any characters (by default with space).
xxxxxxxxxx
1
function repeatText(count, text) {
2
var result = '';
3
for (var i = 0; i < count; ++i) {
4
result += text;
5
}
6
return result;
7
}
8
9
function replaceText(text, insert, index, spacer) {
10
if (spacer == null) {
11
spacer = ' ';
12
}
13
var prefix = text.substring(0, index);
14
var postfix = text.substring(index + insert.length);
15
var space = repeatText(index - text.length, spacer);
16
17
return prefix + space + insert + postfix;
18
}
19
20
// Usage example:
21
22
console.log( replaceText('This is text.', '__', 0) ); // __is is text.
23
console.log( replaceText('This is text.', '__', 2) ); // Th__ is text.
24
console.log( replaceText('This is text.', '__', 11) ); // This is tex__
25
26
console.log( replaceText('This is text.', '__', 13) ); // This is text.__
27
console.log( replaceText('This is text.', '__', 15) ); // This is text. __
28
29
console.log( replaceText('text...', '__', 10, '++') ); // text...++++++__
ES 2015 introduced repeat()
method for string.
xxxxxxxxxx
1
const replaceText = (text, insert, index, spacer = ' ') => {
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
// Usage example:
10
11
console.log( replaceText('This is text.', '__', 0) ); // __is is text.
12
console.log( replaceText('This is text.', '__', 2) ); // Th__ is text.
13
console.log( replaceText('This is text.', '__', 11) ); // This is tex__
14
15
console.log( replaceText('This is text.', '__', 13) ); // This is text.__
16
console.log( replaceText('This is text.', '__', 15) ); // This is text. __
17
18
console.log( replaceText('text...', '__', 10, '++') ); // text...++++++__