javascript 如何替换“<b>” 在整个文档中带有“<b>”并且没有 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12450381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:14:02  来源:igfitidea点击:

How to replace "&lt;b&gt;" with "<b>" in the whole document and without jquery

javascriptreplace

提问by dasmax

The following function only replaces the first "&lt;br /&gt;" 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.

下面的函数只替换&lt;br /&gt;它找到的第一个“ ”,而不是后面的。有谁知道如何解决这个问题?我希望该函数替换整个文档中的所有字符串。

<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

谢谢

回答by Eric

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

使用正则表达式和g(全局)标志:

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:

另一种选择是使用.split(find).join(replace)习语:

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

回答by Anoop

following code should solve your problem:

以下代码应该可以解决您的问题:

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

回答by sapht

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.

如果文档是动态的,如由脚本、PHP 或其他方式生成的,最好在数据库中或在打印数据时替换标签。如果是静态 HTML 页面,最好在原始文件中编辑代码。

Dynamically replacing the entire body after page load is going to perform slowly.

页面加载后动态替换整个正文将执行缓慢。