I need a javascript that replaces some words on my web page with other words. So when th开发者_开发百科e 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?
<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 common.
精彩评论