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()
Another option:
$("<p>").html(myContent).text();
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"
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.
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,""));
});
Source: Stackoverflow.com