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
How to replace "<b>" with "<b>" in the whole document and without jquery
提问by dasmax
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.
下面的函数只替换<br />
它找到的第一个“ ”,而不是后面的。有谁知道如何解决这个问题?我希望该函数替换整个文档中的所有字符串。
<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
谢谢
回答by Eric
Use regular expressions, and the g
(global) flag:
使用正则表达式和g
(全局)标志:
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:
另一种选择是使用.split(find).join(replace)
习语:
document.body.innerHTML = document.body.innerHTML
.split('<br />').join('<br />')
.split('<b>').join('<b>')
.split('</b>').join('</b>');
回答by Anoop
following code should solve your problem:
以下代码应该可以解决您的问题:
document.body.innerHTML = document.body.innerHTML.replace(/</g, '<').
replace(/>/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.
页面加载后动态替换整个正文将执行缓慢。