删除字符串中的所有 HTML 标签(使用 jquery text() 函数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7889765/
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
Remove all HTMLtags in a string (with the jquery text() function)
提问by Peter
is it possible to use the jquery text() function to remove all HTML in a string?
是否可以使用 jquery text() 函数删除字符串中的所有 HTML?
String with HTML tags:myContent = '<div id="test">Hello <span>world!</span></div>';
带有 HTML 标签的字符串:myContent = '<div id="test">Hello <span>world!</span></div>';
The result must be:Hello world!
结果必须是:Hello world!
回答by Ross Dargan
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
这导致你好世界。这是否回答你的问题?
http://jsfiddle.net/D2tEf/for an example
回答by Johann Myburgh
I created this test case: http://jsfiddle.net/ccQnK/1/, I used the Javascript replace function with regular expressions to get the results that you want.
我创建了这个测试用例:http: //jsfiddle.net/ccQnK/1/,我使用带有正则表达式的 Javascript 替换函数来获得你想要的结果。
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
回答by Radek Pech
If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.
如果您需要删除 HTML 但不知道它是否确实包含任何 HTML 标记,则不能直接使用 jQuery 方法,因为它返回非 HTML 文本的空包装器。
$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""
You must either wrap the text in valid HTML:
您必须将文本包装在有效的 HTML 中:
$('<div>' + 'Hello world' + '</div>').text();
Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:
或者使用可以处理 HTML 和非 HTML 文本的方法 $.parseHTML()(自 jQuery 1.8 起):
var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method
Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.
加上 parseHTML 完全删除脚本标签,这对于用户输入的反黑客保护非常有用。
$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"
$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"
回答by James Allardice
回答by Hemerson Varela
Another option:
另外一个选项:
$("<p>").html(myContent).text();
回答by Danny van Holten
I found in my specific case that I just needed to trim the content. Maybe not the answer asked in the question. But I thought I should add this answer anyway.
我发现在我的具体情况下,我只需要修剪内容。也许不是问题中提出的答案。但我想无论如何我都应该添加这个答案。
$(myContent).text().trim()