innerHTML.replace() method behavior discrepancy in IE/Win

Discussion in 'JavaScript' started by heathkornblum, Apr 24, 2006.

  1. #1
    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;
    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
     
    heathkornblum, Apr 24, 2006 IP
  2. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #2


    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');
    
    Code (markup):
    I didn't know this, but it took only a moment to alert the values and see the results.
     
    Logic Ali, Apr 24, 2006 IP
  3. torunforever

    torunforever Peon

    Messages:
    414
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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);
    }
     
    torunforever, Apr 24, 2006 IP
  4. heathkornblum

    heathkornblum Guest

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That was very helpful. :)
     
    heathkornblum, Apr 24, 2006 IP