<!DOCTYPE html>
<html>
<head>
<title>
Replace all occurrences of a string in HTML page with jquery
</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js" type="text/javascript"></script>
<script>
$(function() {
// replace function replace "xyz.com" to "www.ourNewSite.com" without regular expression
$('#btnReplaceWithOutRegularExpression').click(function() {
var obj0 = $('#Sitecontent');
var pos = 0;
var replaceTo = "oldsite.com"
var replaceWith = "www.ournewsite.com";
while (pos !== -1) {
pos = obj0.html().indexOf(replaceTo, pos); //indexOf return the index position of text
if (pos != -1) // loop run till string exists in document
{
obj0.html(obj0.html().replace(replaceTo, replaceWith))
pos = pos + replaceWith.length;
}
}
});
// replace function replace "xyz.com" to "www.ourNewSite.com" with the help of regular expression
$('#btnReplaceWithRegularExpression').click(function() {
var obj0 = $('#Sitecontent1');
var replaceTo = /oldsite.com/g
var replaceWith = "www.ournewsite.com";
obj0.html(obj0.html().replace(replaceTo, replaceWith))
});
});
</script>
</head>
<body>
<button id="btnReplaceWithOutRegularExpression">Replace oldsite.com to www.ournewsite.com without regular expression</button><br><br>
<button id="btnReplaceWithRegularExpression">Replace oldsite.com to www.ournewsite.com with regular expression</button>
<br> <br>
<div id="Sitecontent">
<P dir="ltr" style="text-align: left;" trbidi="on">
Welcome to oldsite.com.
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
In oldsite.com we work on latest technologies.
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
Our Office
oldsite.com
xxx xx
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
Thanks
oldsite.com
</P>
</div>
<br>
<div id="Sitecontent1">
<P dir="ltr" style="text-align: left;" trbidi="on">
Welcome to oldsite.com.
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
In oldsite.com we work on latest technologies.
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
Our Office
oldsite.com
xxx xx
</P>
<P dir="ltr" style="text-align: left;" trbidi="on">
Thanks
oldsite.com
</P>
</div>
</body>
</html>
// Code goes here
/* Styles go here */