Remove html tag from string using jQquery

I want to remove an HTML tag from a string, e.g. remove div, p, br, ...

I am trying to do this:

var mystring = "<div><p>this</p><p>is</p><p>my</p><p>text</p><p>sample</p><p> </p><p> </p></div>" var html3 = $(mystring).text(); 

but the result:

 "thisismytextsample " 

How to do it: "this is my sample text"

+5
source share
3 answers

You can use the replace function:

 var mystring="<div><p>this</p><p>is</p><p>my</p><p>text</p></div>" var stripped = mystring.replace(/(<([^>]+)>)/ig," "); // this is my text 

source: http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

+1
source

You can get all the text of the p tag in an array, and then append them to spaces:

 $(mystring).find('p').map(function() { return $(this).text(); }).toArray().join(' ')); 

Working demo

+4
source

Try this using regex

 var mystring="<div><p>this</p><p>is</p><p>my</p><p>text</p><p>sample</p><p> </p><p> </p></div>" function RemoveHTMLTags(string1) { var regX = /(<([^>]+)>)/ig; var html = string1; return html.replace(regX, " "); } var res = RemoveHTMLTags(mystring); alert(res); 

Demo

+1
source

Source: https://habr.com/ru/post/1200100/


All Articles