如何从JavaScript字符串中剥离HTML ?
当前回答
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
这几乎是最好的方式,你让浏览器做它最擅长的事情——解析HTML。
编辑:正如下面的评论所指出的,这不是最跨浏览器的解决方案。最跨浏览器的解决方案是递归遍历元素的所有子元素,并连接找到的所有文本节点。但是,如果你正在使用jQuery,它已经为你做了:
alert($("<p>Hello, <b>World</b></p>").text());
查看文本方法。
其他回答
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
这几乎是最好的方式,你让浏览器做它最擅长的事情——解析HTML。
编辑:正如下面的评论所指出的,这不是最跨浏览器的解决方案。最跨浏览器的解决方案是递归遍历元素的所有子元素,并连接找到的所有文本节点。但是,如果你正在使用jQuery,它已经为你做了:
alert($("<p>Hello, <b>World</b></p>").text());
查看文本方法。
在当前的浏览器中,使用浏览器的解析器可能是最好的选择。下面的方法可以工作,但有以下注意事项:
Your HTML is valid within a <div> element. HTML contained within <body> or <html> or <head> tags is not valid within a <div> and may therefore not be parsed correctly. textContent (the DOM standard property) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent. The HTML does not contain <script> elements. The HTML is not null The HTML comes from a trusted source. Using this with arbitrary HTML allows arbitrary untrusted JavaScript to be executed. This example is from a comment by Mike Samuel on the duplicate question: <img onerror='alert(\"could run arbitrary JS here\")' src=bogus>
代码:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
从这个网站(web. achieve)提炼。
这个正则表达式查找<,一个可选的斜杠/,一个或多个不是>的字符,然后是>或$(行尾)
例子:
'<div>Hello</div>' ==> 'Hello'
^^^^^ ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
^^
但它也不是无懈可击的:
'If you are < 13 you cannot register' ==> 'If you are '
^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
^^^^^^^^^^^^^^^^^^ ^^^^^^
如果有人试图破坏您的应用程序,此正则表达式将无法保护您。只有在您已经知道输入格式的情况下才应该使用它。正如其他知识渊博且大多理智的人所指出的,要安全地剥离标记,必须使用解析器。
如果您无法访问像DOM这样方便的解析器,并且您不能相信您的输入是正确的格式,那么您最好使用像sanitize-html这样的包,以及其他可用的sanitizer。
我知道这个问题有一个公认的答案,但我觉得它并不是在所有情况下都适用。
为了完整起见,因为我花了太多时间在这上面,下面是我们所做的:我们最终使用了PHP .js中的一个函数(对于那些更熟悉PHP的人来说,这是一个非常好的库,但也会时不时地做一些JavaScript):
http://phpjs.org/functions/strip_tags:535
这似乎是唯一一段JavaScript代码,它成功地处理了我塞进应用程序中的所有不同类型的输入。也就是说,在不破坏它的情况下-请参阅我上面关于<script />标记的评论。
推荐文章
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?
- 清除JavaScript中的缓存