Reputation: 41
The following function only replaces the first "<br />
" it finds, not the following ones. Does anyone know how to fix that problem?
I want the function to replace all the strings in the whole document.
<script language="javascript" type="text/javascript">
window.onload = function umtauschen()
{
document.body.innerHTML = document.body.innerHTML.replace('<br />', '<br />');
document.body.innerHTML = document.body.innerHTML.replace('<b>', '<b>');
document.body.innerHTML = document.body.innerHTML.replace('</b>', '</b>');
}
</script>
Thanks
Upvotes: 2
Views: 15392
Reputation: 2829
If the document is dynamic, as in generated by a script, PHP or otherwise, it's better idea to replace the tags in the DB or while printing the data. If it's a static HTML page, it's a better idea to edit code in the original file.
Dynamically replacing the entire body after page load is going to perform slowly.
Upvotes: 1
Reputation: 97641
Use regular expressions, and the g
(global) flag:
document.body.innerHTML = document.body.innerHTML
.replace(/<br \/>/g, '<br />')
.replace(/<b>/g, '<b>')
.replace(/<\/b>/g, '</b>');
Another option is to use the .split(find).join(replace)
idiom:
document.body.innerHTML = document.body.innerHTML
.split('<br />').join('<br />')
.split('<b>').join('<b>')
.split('</b>').join('</b>');
Upvotes: 5
Reputation: 23208
following code should solve your problem:
document.body.innerHTML = document.body.innerHTML.replace(/</g, '<').
replace(/>/g, '>') ;
Upvotes: 1