Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove HTML tags from textarea with JavaScript

I'm loading text from database but I'd like to remove html link code from it with JavaScript.

So lets say the textarea right now displays:

<a rel="nofollow" href="http://stackoverflow.com//questions/ask">http://stackoverflow.com//questions/ask</a> - good page 

and I want it to display:

http://stackoverflow.com//questions/ask - good page

Is there something lightweight I could use that would work for multiple links in the same textarea?

like image 358
MatBanik Avatar asked Jul 11 '26 07:07

MatBanik


1 Answers

Inspired by this answer, use the browser's HTML parsing abilities to get this done right.

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}
jQuery('#textareaid').text(function(index, text){
 return strip(text);
});

Here's the JSFiddle of it working: http://jsfiddle.net/Au95R/1/

(Edited to use cleaner JS)

like image 127
Yahel Avatar answered Jul 13 '26 22:07

Yahel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!