Is there an easy way to take a string of html in JavaScript and strip out the html?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
If you're running in a browser, then the easiest way is just to let the browser do it for you...
Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can still let the browser do the work for you - see Saba's answer on using the now widely-available DOMParser.
Simplest way:
That retrieves all the text from a string of html.
As an extension to the jQuery method, if your string might not contian HTML (eg if you are trying to remove HTML from a form field)
jQuery(html).text();
will return an empty string if there is no html
Use:
jQuery('<p>' + html + '</p>').text();
instead.
Update: As has been pointed out in the comments, in some circumstances this solution will execute javascript contained within
html
if the value ofhtml
could be influenced by an attacker, use a different solution.After trying all of the answers mentioned most if not all of them had edge cases and couldn't completely support my needs.
I started exploring how php does it and came across the php.js lib which replicates the strip_tags method here: http://phpjs.org/functions/strip_tags/
Using Jquery:
Another, admittedly less elegant solution than nickf's or Shog9's, would be to recursively walk the DOM starting at the <body> tag and append each text node.