dasmax
dasmax

Reputation: 41

How to replace "<b>" with "<b>" in the whole document and without jquery

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('&lt;br /&gt;', '<br />');
    document.body.innerHTML = document.body.innerHTML.replace('&lt;b&gt;', '<b>');
    document.body.innerHTML = document.body.innerHTML.replace('&lt;/b&gt;', '</b>');
    }
</script>

Thanks

Upvotes: 2

Views: 15392

Answers (3)

sapht
sapht

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

Eric
Eric

Reputation: 97641

Use regular expressions, and the g (global) flag:

document.body.innerHTML = document.body.innerHTML
    .replace(/&lt;br \/&gt;/g, '<br />')
    .replace(/&lt;b&gt/g, '<b>')
    .replace(/&lt;\/b&gt;/g, '</b>');

Another option is to use the .split(find).join(replace) idiom:

document.body.innerHTML = document.body.innerHTML
    .split('&lt;br /&gt;').join('<br />')
    .split('&lt;b&gt;').join('<b>')
    .split('&lt;/b&gt;').join('</b>');

Upvotes: 5

Anoop
Anoop

Reputation: 23208

following code should solve your problem:

document.body.innerHTML = document.body.innerHTML.replace(/&lt;/g, '<').
                                                replace(/&gt;/g, '>') ;

Upvotes: 1

Related Questions