is it possible to use the jquery text() function to remove all HTML in a string?
String with HTML tags:myContent = \'
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.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
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
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.
$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""
You must either wrap the text in valid HTML:
$('<div>' + 'Hello world' + '</div>').text();
Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:
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.
$('<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"
Another option:
$("<p>").html(myContent).text();
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()
Could you not just try it?
myContent = '<div id="test">Hello <span>world!</span></div>';
console.log($(myContent).text()); //Prints "Hello world!"
Note that you need to wrap the string in a jQuery object, otherwise it won't have a text
method obviously.