Debt Consolidation - Record Internet Radio with Tags - Debt Consolidation - Debt Consolidation - Credit Card Debt Consolidation

PDA

View Full Version : innerHTML.replace() method behavior discrepancy in IE/Win


heathkornblum
Apr 24th 2006, 7:39 am
This one has stumped me for a couple days now and I need some help if you can figure it out. When I run the following piece of code in Firefox or Safari, the result is a page that says: stuff NEW with NEW

But, if I run this code in IE for Windows all I get is: NEW

The replace function seems to replace my entire text chunk with a replacement fragment rather than replacing simply occurences of regex hits.

The regular expression looks for text surrounded by two dots and replaces those hits with "NEW".

Here's the chunk as an HTML page:

<html>
<head>
<script>
function rewritestuff(bodytext)
{
var pattern=/\.\.(.+?)\.\./g;
var tags=bodytext.match(pattern);
for (var i in tags) {
var tag=tags[i];
bodytext=bodytext.replace(tag, 'NEW');
if (i == tags.length - 1) break;
}
document.write(bodytext);
}
</script>
</head>
<body onload='rewritestuff(document.body.innerHTML)'>
stuff ..things.. with ..otherthings..
</body>
</html>

Any help you can offer will be very well appreciated. I haven't seen anyone else posting a problem quite like this. Is this a bug or a feature :) ?

Thanks,

Heath

Logic Ali
Apr 24th 2006, 11:42 am
for (var i in tags) {
var tag=tags[i];



In I.E. this exposes other properties of the array other than the matches.

Do it properly:

for(var i=0; i<tags.length; i++)
bodytext=bodytext.replace(tags[i], 'NEW');

I didn't know this, but it took only a moment to alert the values and see the results.

torunforever
Apr 24th 2006, 12:01 pm
Logic Ali is correct that doing the for in exposes properties such as 'input' and 'lastIndex' in IE. The 'input' property contains the whole string, so you end up replacing everything with 'NEW'

I'd like to add that the code can be even further simplied.

function rewritestuff(bodytext)
{
var pattern=/\.\.(.+?)\.\./g;
bodytext=bodytext.replace(pattern, 'NEW');
document.write(bodytext);
}

heathkornblum
Apr 24th 2006, 9:57 pm
That was very helpful. :)