How to remove HTML tags using jQuery?

I want to remove HTML tags from a string. For example, suppose we have a line:

<p> example ive got a string</P> 

How can I write a function that removes <p><p> and returns only "example, I have a string"?

+49
jquery
Oct 30 '12 at 13:27
source share
4 answers

the safest way is to rely on the browser text field to properly avoid the content. Here is an example:

 function stripHTML(dirtyString) { var container = document.createElement('div'); var text = document.createTextNode(dirtyString); container.appendChild(text); return container.innerHTML; // innerHTML will be a xss safe string } document.write( stripHTML('<p>some <span>content</span></p>') ); document.write( stripHTML('<script><p>some <span>content</span></p>') ); 

Remember that the browser accesses special TextNodes characters when we access the html lines ( innerHTML , outerHTML ). For comparison, accessing text values ​​( innerText , textContent ) will result in raw strings, which means they are unsafe and may contain XSS.

If you use jQuery , then using .text() safe and backward compatible. See Other answers to this question.

The easiest way in pure JavaScript if you work with browsers. <= Internet Explorer 8:

 string.replace(/(<([^>]+)>)/ig,""); 

But there is a problem with parsing HTML with regular expression, so this will not provide very good security. Also, this only applies to HTML characters, so it is not completely safe for xss.

+67
Oct 30 '12 at 13:30
source share

Use the .text() function:

 var text = $("<p> example ive got a string</P>").text(); 

Refresh . As Brilliannd points out below, if the input line does not contain any tags and you are out of luck, it can be thought of as a CSS selector. Thus, this version is more reliable:

 var text = $("<div/>").html("<p> example ive got a string</P>").text(); 
+96
Oct 30 '12 at 13:28
source share

This is an example of getting an image of a URL, which is why you exit the p tag.

Try the following:

 $('#img').attr('src').split('<p>')[1].split('</p>')[0] 
+2
May 13, '15 at 12:18
source share

You can use existing split function

One simple and mutable example:

 var str = '<p> example ive got a string</P>'; var substr = str.split('<p> '); // substr[0] contains "" // substr[1] contains "example ive got a string</P>" var substr2 = substr [1].split('</p>'); // substr2[0] contains "example ive got a string" // substr2[1] contains "" 

This example shows how split works.

+1
Oct 30 '12 at 13:36
source share



All Articles