Parse Page

Discussion in 'JavaScript' started by Kennedy, Feb 20, 2008.

  1. #1
    Is there a way to change every occurrence of a word into another word.

    For example, you have the Javascript code at the top of the page that changes the word "brown" to "red". The sentence in the page is:

    The quick brown fox.

    But with the Javascript code, it displays like this:

    The quick red fox.

    I know there is a way to do this with Java (its basically how contextual link ad services like Kontera work), I just don't know how do it.
     
    Kennedy, Feb 20, 2008 IP
  2. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
  3. Kennedy

    Kennedy Peon

    Messages:
    994
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    But how would I get the whole page into a string, change it, then display it as the changed format?
     
    Kennedy, Feb 21, 2008 IP
  4. Kennedy

    Kennedy Peon

    Messages:
    994
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Here's what I have so far. But it doesn't work:

    <body onload="document.getElementById('mydiv').replace(/test/, "sentence");">
    <div id="mydiv">This is a test!</div>

    It should output:
    This is a sentence!
    on the page, but it doesn't.
     
    Kennedy, Feb 21, 2008 IP
  5. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #5
    You would need to reset the div's inner HTML with the returned replace string. Also, you can't put double quotations around the word sentence in the replace string since you used quotations as the opening/closing for the onload event.

    <body onload="document.getElementById('mydiv').innerHTML = document.getElementById('mydiv').innerHTML.replace(/test/ig, 'sentence');">
    <div id="mydiv">This is a test!</div>
    HTML:
    One more thing: I put ig after the / of /test/. The 'i' means it's case insensitive (meaning it will also replace Test and TEST) and the 'g' means global so it will replace all instances of the word test and not just the first. You can remove either or both of these letter modifiers if you please.
     
    zerxer, Feb 21, 2008 IP
  6. Kennedy

    Kennedy Peon

    Messages:
    994
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #6
    awesome, thanks! works perfectly!
     
    Kennedy, Feb 21, 2008 IP