Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove HTML Tags in Javascript with Regex

I am trying to remove all the html tags out of a string in Javascript. Heres what I have... I can't figure out why its not working....any know what I am doing wrong?

<script type="text/javascript">  var regex = "/<(.|\n)*?>/"; var body = "<p>test</p>"; var result = body.replace(regex, ""); alert(result);  </script> 

Thanks a lot!

like image 625
Gabe Avatar asked Sep 30 '09 18:09

Gabe


People also ask

How do you remove tags in HTML?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

How remove HTML tag from string in react?

To remove html tags from string in react js, just use the /(<([^>]+)>)/ig regex with replace() method it will remove tags with their attribute and return new string.

What is HTML regex?

HTML stands for HyperText Markup Language and is used to display information in the browser. HTML regular expressions can be used to find tags in the text, extract them or remove them.

How do I strip a string in HTML?

To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.


1 Answers

Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:

var regex = /(<([^>]+)>)/ig ,   body = "<p>test</p>" ,   result = body.replace(regex, "");  console.log(result); 

If you're willing to use a library such as jQuery, you could simply do this:

console.log($('<p>test</p>').text()); 
like image 64
karim79 Avatar answered Oct 12 '22 10:10

karim79