Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all html tags from a string [duplicate]

Hi I am trying to remove all the html tags from a particular string its showing error.

Here is my string:

<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>

My jQuery code is here:

var item = <p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>;
item = item.replace(/~/g, '');
item = item.replace(/<p>/g, '');
item = item.replace('</p>'/g, '');
var splitArray = item.split('<br />');
var l = splitArray.length;
for (var i = 0; i < l; i++) {
    out = out + "<li><span class='sp_icon sp_star_icon'></span> "
          + splitArray[i].trim() + "</li>";
}
console.log(item);
like image 365
Suresh Pattu Avatar asked Jul 20 '15 12:07

Suresh Pattu


2 Answers

With vanilla JS you can do it like this

var item = '<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>';

function getText(html) {
    var tmp = document.createElement('div');
    tmp.innerHTML = html;
    
    return tmp.textContent || tmp.innerText;
}

console.log(getText(item));
like image 86
Oleksandr T. Avatar answered Sep 27 '22 22:09

Oleksandr T.


You can strip out all the html-tags with a regular expression: /<(.|\n)*?>/g

Described in detail here: http://www.pagecolumn.com/tool/all_about_html_tags.htm

In your JS-Code it would look like this:

item = item.replace(/<(.|\n)*?>/g, '');
like image 32
plexus Avatar answered Sep 27 '22 21:09

plexus