How to strip HTML tags from string in JavaScript?
Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:
- Your HTML is valid within a
<div>
element. HTML contained within<body>
or<html>
or<head>
tags is not valid within a<div>
and may therefore not be parsed correctly. textContent
(the DOM standard property) andinnerText
(non-standard) properties are not identical. For example,textContent
will include text within a<script>
element whileinnerText
will not (in most browsers). This only affects IE <=8, which is the only major browser not to supporttextContent
.- The HTML does not contain
<script>
elements. - The HTML is not
null
- The HTML comes from a trusted source. Using this with arbitrary HTML allows arbitrary untrusted JavaScript to be executed. This example is from a comment by Mike Samuel on the duplicate question:
<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>
Code:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
Remove HTML tags from a String
Use a HTML parser instead of regex. This is dead simple with Jsoup.
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
Jsoup also supports removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. <b>
, <i>
and <u>
.
See also:
- RegEx match open tags except XHTML self-contained tags
- What are the pros and cons of the leading Java HTML parsers?
- XSS prevention in JSP/Servlet web application
How to remove HTML tag (not a specific tag ) with content from a string in javascript
Removing all HTML tags and the innerText can be done with the following snippet. The Regexp captures the opening tag's name, then matches all content between the opening and closing tags, then uses the captured tag name to match the closing tag.
const regexForStripHTML = /<([^</> ]+)[^<>]*?>[^<>]*?<\/\1> */gi;
const text = "OCEP <sup>®</sup> water product";
const stripContent = text.replaceAll(regexForStripHTML, '');
console.log(text);
console.log(stripContent);
How can I remove HTML tags other than div and span from a string in JavaScript?
To remove all tags excluding specific tags, you can use the following regular expression.
const str = "<div><p></p><span></span></div>";
console.log(str.replace(/(<\/?(?:span|div)[^>]*>)|<[^>]+>/ig, '$1'));
Strip HTML from Text JavaScript
If you're running in a browser, then the easiest way is just to let the browser do it for you...
function stripHtml(html)
{
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
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.
How do I remove all HTML tags from a string without knowing which tags are in it?
You can use a simple regex like this:
public static string StripHTML(string input)
{
return Regex.Replace(input, "<.*?>", String.Empty);
}
Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of 'Mark E. Haase'/@mehaase)
Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?
How to remove all html tags including ' ' from string?
The text looks to be double-escaped, kinda - first turn all the &
s into &
s, so that the HTML entities can be properly recognized. Then .text()
will give you the plain text version of the HTML markup.
const input = `<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>\n\n<p> </p>\n\n<p>TItle </p>\n`;
const inputWithProperEntities = input.replaceAll('&', '&');
console.log($(inputWithProperEntities).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Is there a way to remove html tags from a string in JavaScript?
You can achieve this by JavaScript
.
Try this!!
var plainText = content.replace(/<[^>]*>/g, '');
This will return you plain text.
Related Topics
Is There a Java Equivalent or Methodology For the Typedef Keyword in C++
Override Back Button to Act Like Home Button
Java Using Much More Memory Than Heap Size (Or Size Correctly Docker Memory Limit)
Add a Complex Image in the Panel, With Buttons Around It in One Customized User Interface
Validating Input Using Java.Util.Scanner
Recommendations For a Heap Analysis Tool For Java
Why Is Using a Wild Card With a Java Import Statement Bad
Calling a Java Method from C++ in Android
Broadcast Receiver For Checking Internet Connection in Android App
One Time Login in App - Firebaseauth
Error: Could Not Find or Load Main Class
How to Add Jtable in Jpanel With Null Layout
How to Test a Class That Has Private Methods, Fields or Inner Classes
How to Retrieve and Display Images from a Database in a Jsp Page