Reputation: 10052
I have a variable (in this example var str = "I!%1$s-I!%2$s TTL!%3$s";
), in which I want to replace the %
with elements from an array (var regex = ['aaa', 'bbb', 'ccc'];
).
I google around a bit and found this solution, but I'm having trouble implementing it. My problem is that I want to replace a single character with multiple characters, and then continue the string, but this just overwrites the characters. I actually have no idea why.
Any help is appreciated, my code below
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
}
var str = "I!%1$s-I!%2$s TTL!%3$s";
var regex = ['replace', 'replace', 'replace'];
//find position of %
var find = /%/gi,
result, pos = [];
while ((result = find.exec(str))) {
pos.push(result.index);
}
//replace % with regex elements
for (x = 0; x < pos.length; x++) {
str = str.replaceAt(pos[x], regex[x]);
}
document.write(str);
Upvotes: 3
Views: 170
Reputation: 239483
Use replacement function, like this
var str = "I!%1$s-I!%2$s TTL!%3$s";
var regex = ['[123]', '[456]', '[789]'];
console.log(str.replace(/%(\d+)/g, function(match, group1) {
return regex[parseInt(group1) - 1] + group1;
}));
// I![123]1$s-I![456]2$s TTL![789]3$s
The RegEx /%(\d+)/g
matches anything of the pattern %
followed by one or more digits. And it captures the digits as a group. Then the exact match and the group is passed to the function to get the actual replacement. In the function, you convert the group to a number with parseInt
and return the respective value from the regex
array.
Upvotes: 3