PDA

View Full Version : What does RegExp.exec() return?


Spudhead
06-14-2005, 12:07 PM
Hi :)

Due to a bit of XSL-related hassle we were having, I've written the following function to replace all the HTML entity codes in a string with their corresponding entity names:


function cleanEntityNames(str){

var re1 = /&#[0-9]{2,4};/;
var re2 = /[0-9]{2,4}/;

while (re1.test(str)){

aResults1 = re1.exec(str);
match = aResults1[0];

aResults2 = re2.exec(match);
entityRef = aResults2[0];

replacement = String.fromCharCode(entityRef);

str = str.replace(match, replacement);

}

return str;

}


Now it works fine, but it's a bit inelegant. The bit I'm concerned about is this:

aResults1 = re1.exec(str);
match = aResults1[0];

All the references I've looked at say that re.exec(str) will return the first match found in str - but in an array.

Why is it returning an array if the array is just going to contain one item?

:confused:

Harry Armadillo
06-14-2005, 01:12 PM
A regular expression can contain parenthetical elements, used for back-referencing or sub-expressions. exec returns an array to allow access to these parenthetical matches as well as the overall match.

For exampe:

/c(a|u)t/.exec("cat"); // returns ['cat','a'], an array holding the match and a parenthetical match
/(http|https|ftp):\/\/(^[\/]+)/.exec('http://foo.bar/file.ext') // returns ['http://foo.bar', 'http', 'foo.bar']

Apply that to your function...function cleanEntityNames(str) {
var regex = /&#([0-9]{2,4});/;
while (match=regex.exec(str)) {
replacement = String.fromCharCode(match[1]);
str = str.replace(match[0], replacement);
}
return str;
}

Spudhead
06-14-2005, 02:52 PM
Aha :) Nice one, thanks.