
Originally Posted by
Twey
I have a string, in which I want to match /\\e\[([^m]+)m/g, and replace it with a value pulled out of an array, the index of which should be \1.
Just to clarify, Twey, you have a string that may contain one or more sequences in a string that would match \e[XXm where XX is a number[1], and you want to replace that entire sequence with the value from the array with the aforementioned numeric index?
Yes. 
The problem is that String.replace() doesn't parse \# until it's actually called, and the value needs to be taken from the array before the call happens.
When using a string for the second argument, yes. It's simple, though, using a function argument:
Code:
string.replace(/\\e\[([^m]+)m/g, function(match, index) {
return array[index];
});
Unfortunately, some browsers (such as IE5) won't support this, so you might need to take a completely different approach:
Code:
var pattern = /\\e\[([^m]+)m/g,
result = '',
index = 0,
matches;
while((matches = pattern.exec(string))) {
result += string.substring(index, matches.index)
+ array[matches[1]];
index = pattern.lastIndex;
}
result += string.substring(index);
Mike
[1] I assume it's a number, otherwise an array is inappropriate and an object (literal) would be better (and might do anyway). Moreover, if it is a number, then [^m] could be replaced with \d.
Bookmarks