How to Strip HTML Tags from String in JavaScript

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) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent.
  • 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 || "";

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 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 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&nbsp;is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry&#39;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>

How to remove html tags from an Html string using RegEx?

You can use

.replace(/<br>(?=(?:\s*<[^>]*>)*$)|(<br>)|<[^>]*>/gi, (x,y) => y ? ' & ' : '')

See the JavaScript demo:

const text = '<div class="ExternalClassBE95E28C1751447DB985774141C7FE9C"><p>Tina Schmelz<br></p><p>Sascha Balke<br></p></div>';
const regex = /<br>(?=(?:\s*<[^>]*>)*$)|(<br>)|<[^>]*>/gi;
console.log(
text.replace(regex, (x,y) => y ? ' & ' : '')
);

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'));

How to remove all html tags from a string

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, '');

Unable to remove HTML tags from string

Approach using angular.element(html).text()

angular.module('app', [])
.controller('main', function() {
var jobDescription = "<P> kajskjdhkj</p> <div> lakjsklj</div>";
this.txt = angular.element(jobDescription).text()

var sample ="Abc. Xyz Lmn No.1234 H, PPP TTT GGG, LKH 3</br>"
this.txt2 = angular.element('<div>').html(sample).text()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="app" ng-controller="main as $ctrl">
{{$ctrl.txt}}<br/><br/>
{{$ctrl.txt2}}
</div>

Remove specific HTML tag with its content from javascript string

You should avoid parsing HTML using regex. Here is a way of removing all the <a> tags using DOM:

// your HTML textvar myString = '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>';myString += '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>'myString += '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>'
// create a new dov containervar div = document.createElement('div');
// assing your HTML to div's innerHTMLdiv.innerHTML = myString;
// get all <a> elements from divvar elements = div.getElementsByTagName('a');
// remove all <a> elementswhile (elements[0]) elements[0].parentNode.removeChild(elements[0])
// get div's innerHTML into a new variablevar repl = div.innerHTML;
// display itconsole.log(repl)
/*<table><tbody><tr><td>Some text ...</td></tr></tbody></table><table><tbody><tr><td>Some text ...</td></tr></tbody></table><table><tbody><tr><td>Some text ...</td></tr></tbody></table>*/

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


Related Topics



Leave a reply



Submit