admin管理员组

文章数量:1420918

I need a javascript that replaces some words on my web page with other words. So when the page loads, some words that I specify get replaced by something else

For example, if "hello" is found replace with "hi" if "one" is found replace with "two" etc.

How can I do that?

I need a javascript that replaces some words on my web page with other words. So when the page loads, some words that I specify get replaced by something else

For example, if "hello" is found replace with "hi" if "one" is found replace with "two" etc.

How can I do that?

Share Improve this question edited Aug 19, 2015 at 18:53 ale10ander 1,0065 gold badges23 silver badges44 bronze badges asked Feb 18, 2011 at 15:56 Dave819Dave819 6113 gold badges11 silver badges14 bronze badges 2
  • Does it need to be sequential or random? – TNC Commented Feb 18, 2011 at 15:58
  • 1 TIL I learned that stackoverflow doesn't let you post let me google that for you links – Mike Robinson Commented Feb 18, 2011 at 15:59
Add a ment  | 

2 Answers 2

Reset to default 2
<div id="myDiv">
hello there my name is tom there hello there
</div>

<button onclick="replaceText()">Click me!</button>

With the JS:

function replaceText(){
    var theDiv = document.getElementById("myDiv");
    var theText = theDiv .innerHTML;

    // Replace words
    theText = theText.replace("word", "replace");
    theText = theText.replace("one", "fish");
    theText = theText.replace("tom", "drum");

    theDiv.innerHTML = theText;
}

You can insert a regular expression in the first parameter of the replace function if you want to avoid ruining tag markup (if for some reason you are replacing words like 'div' or 'strong'). But this function will work perfectly fine for plain text blocks.

in jquery, add this to a script tag in your head tag

$(document).ready(function() {
  $("p, div, span, li").each(function() {
   this.text(this.text().replace("word", "new word").replace("word2", "new word2"));
  });
});

you need to add to the list of tags any tags where you want text replacing, I've simply added the most mon.

本文标签: javascript a function to replace some words on my webpageStack Overflow