Search and replace question

Discussion in 'JavaScript' started by Brewster, Jan 23, 2008.

  1. #1
    Hi all

    Is it possible to to get javascript to search for words/strings within html body tags and replace them with different words/strings?

    Any help would be much appriciated.

    Thanks,
    Brew
     
    Brewster, Jan 23, 2008 IP
  2. mjamesb

    mjamesb Member

    Messages:
    88
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    48
    #2
    You can replace the innerHTML...here is a very basic example but be careful as the innerHTML includes tag names and you could mess up your whole page.

    <body>

    <div> keyword </div><br><br>
    <input type="button" onclick="replaceWord('keyword', 'xxxxxxxxxxxxx')" value="Change Keyword To xxxxxxxxxxxxxx">

    <script language="javascript">
    function replaceWord(keyWord, newWord)
    {
    //if you had a single div where the content to search is that would be better....
    //for example if you had a div with and id="test" below would just change to var mystring
    //to var mystring = document.getElementById("test").innerHTML;
    // document.getElementById("test").innerHTML = mystring.replace(keyWord, newWord);
    var mystring = document.body.innerHTML;


    document.body.innerHTML = mystring.replace(keyWord, newWord);
    }

    </script>
    </body>
     
    mjamesb, Jan 23, 2008 IP
    Brewster likes this.
  3. Brewster

    Brewster Active Member

    Messages:
    489
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Thanks for your help. +rep

    Brew
     
    Brewster, Jan 23, 2008 IP