3

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);
Community
  • 1
  • 1
Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163
  • 1
    Maybe a stupid question, but why is using the replace method of a string not an option? – Shilly Aug 18 '15 at 13:26
  • Because you're not updating `pos`. If we have a string `"abc"`, here `"c"` is the 3rd character. If we replace `"b"` with `"foo"` (`"afooc"`), `"c"` is now the 5th character. – James Donnelly Aug 18 '15 at 13:27
  • If I got you right you need to replace te % characters in string with corresponding values from your regex array where index of value corresponds to occurance number of % character in string? – Develoger Aug 18 '15 at 13:28
  • because the array elements are not always the same (.replace replaces all instances of % with a string). I guess I put in a bad example, I'll go edit it out – Miha Šušteršič Aug 18 '15 at 13:28
  • @DušanRadojević yes, that's correct – Miha Šušteršič Aug 18 '15 at 13:29
  • In that case you can even do string.replace in a loop since it will always replace the first occurance of % character... But I vote for @thefourtheye answer – Develoger Aug 18 '15 at 13:32

1 Answers1

3

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497