Clear all tag in html

Remove HTML tag attributes

Except src (img tags) and href (anchor tags)

table style="width: 300px; text-align: center;" border="1" cellpadding="5"> tbody> tr> th width="75">strong>Name strong> th> th colspan="2">span style="font-weight: bold;">Telephone span> th> tr> tr> td>John td> td>a href="tel:0123456785">0123 456 785 a> td> td>img src="images/check.gif" alt="checked" /> td> tr> tbody> table> 
table> tbody> tr> th>strong>Name strong> th> th>span>Telephone span> th> tr> tr> td>John td> td>a href="tel:0123456785">0123 456 785 a> td> td>img src="images/check.gif"/> td> tr> tbody> table> 

This option will leave you the HTML structure but it will remove every attribute (classes, styles and other properties).

Removes classes, inline styles and other tag attributes except the src attribute of image tags and href attributes of anchor tags. We have separated these features because there are individual options to remove the links and images from the HTML source. We decided to implement this feature this way because people never want to end up with a stripped element or a link tag without reference in their code.

Источник

4 Ways to Strip & Remove HTML Tags In Javascript

Welcome to a quick tutorial on how to strip or remove HTML tags in Javascript. Need to extract “text-only” from a string of HTML code? Sanitize a string to make sure there are no HTML tags?

  1. Use regular expression – var txt = HTML-STRING.replace(/(<([^>]+)>)/gi, «»);
  2. Directly extract the text content from an HTML element – var txt = ELEMENT.textContent;
  3. Use the DOM parser then extract the text content –
    • var dom = new DOMParser().parseFromString(HTML-STRING, «text/html»);
    • var txt = dom.body.textContent;
  4. Use a library such as String Strip HTML.

That should cover the basics, but let us walk through more examples – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Strip & Remove HTML Tags In Javascript

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

Читайте также:  Где создавать файлы php

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

STRIP HTML TAGS IN JAVASCRIPT

All right, let us now move into the examples of stripping HTML tags in Javascript.

1) USING REGULAR EXPRESSION

 // (A) STRIP TAGS FUNCTION function stripTags (original) < return original.replace(/(<([^>]+)>)/gi, ""); > // (B) ORIGINAL STRING var str = "

This is a string with some HTML in it.

"; // (C) "CLEANED" STRING var cleaned = stripTags(str); console.log(cleaned);

This method is probably plastered all over the Internet, and regular expression can be very hard to understand. So to keep things easy – replace(/(<([^>]+)>)/gi, «») simply means “replace all with an empty string”. Yep, that effectively removes all HTML tags.

2) TEXT CONTENT

// (A) STRIP TAGS FUNCTION function stripTags (original) < // (A1) CREATE DUMMY ELEMENT & ATTACH HTML let ele = document.createElement("div"); ele.innerHTML = original; // (A2) USE TEXT CONTENT TO STRIP TAGS return ele.textContent; >// (B) ORIGINAL STRING var str = "

This is a string with some HTML in it.

"; // (C) "CLEANED" STRING var cleaned = stripTags(str); console.log(cleaned);

Yep, modern browsers actually come with a very handy NODE.textContent property. Just use that to get the contents of an HTML element, minus all the tags.

3) DOM PARSER & TEXT CONTENT

// (A) STRIP TAGS FUNCTION function stripTags (original) < // (A1) PARSE STRING INTO NEW HTML DOCUMENT let parsed = new DOMParser().parseFromString(original, "text/html"); // (A2) STRIP TAGS, RETURN AS TEXT CONTENT return parsed.body.textContent; >// (B) ORIGINAL STRING var str = "

This is a string with some HTML in it.

"; // (C) "CLEANED" STRING var cleaned = stripTags(str); console.log(cleaned);

This is an alternative to the above. Still using textContent , but we are using the DOMParser instead of createElement . Yes, it does make a difference. More on that in the extras section below.

4) USING STRIP HTML LIBRARY

   

Lastly, for you guys who are on NodeJS – The above textContent will not work since there is effectively no browser. The String Strip HTML library is an alternative you can consider using – Yes, it also works on the “web version” as well.

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

EXTRA – STRIP HTML ENTITES

CREDITS : https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/ function htmlEntities(str) < return String(str).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); >

For the beginners, HTML entities are simply “special characters” to represent certain symbols. For example:

To display HTML code snippets, we have to use HTML entities. E.G.

Foo

should be entered as <p>Foo</p> . To remove HTML entities, we have to use an entirely different regular expression; None of the above “strip HTML” methods will work.

EXTRA – WHICH IS FASTER?

// (A) SOME VERY LONG AND STINKY HTML STRING var str = `LONG LONG HTML STRING HERE`; // (B) REGEX TIMING console.time("REGEX"); var cleaned = str.replace(/(<([^>]+)>)/gi, ""); console.timeEnd("REGEX"); // (C) TEXT CONTENT TIMING console.time("CONTENT"); cleaned = document.createElement("div"); cleaned.innerHTML = str; cleaned = cleaned.textContent; console.timeEnd("CONTENT"); // (D) DOM PARSER console.time("DOMPARSE"); cleaned = new DOMParser().parseFromString(str, "text/html"); cleaned = cleaned.body.textContent; console.timeEnd("DOMPARSE"); // (E) STRIP STRING LIBRARY const < stripHtml >= stringStripHtml; console.time("LIB"); cleaned = stripHtml(str).result; console.timeEnd("LIB");

For you guys who are interested in using the most effective solution – Mirror mirror on the wall, which is the fastest of them all?

Not surprising, regex wins without having to parse anything. DOM parser is faster than creating a dummy element, and the library… grossly inefficient.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

JavaScript removing HTML tags

Learn how to delete all HTML tags using Vanilla JavaScript. See the example code in the Codepen!

I recently needed to remove all HTML tags from the text content of my application to return clean text.

In this case, it was to share a plain text version for meta descriptions. It can also be used for several other outputs.

Today I’ll show you how to remove HTML tags in Javascript.

I’ll show you two ways of removing HTML tags from a string. I want to note that when you accept user input, you should always opt for a more secure server-side check.

One method is to create a temporary HTML element and get the innerText from it.

const original = `

Welcome to my blog

Some more content here


a >2`
; let removeHTML = (input) => let tmp = document.createElement('div'); tmp.innerHTML = input; return tmp.textContent || tmp.innerText || ''; >; console.log(removeHTML(original));

This will result in the following:

'Welcome to my blog Some more content here'

As you can see, we removed every HTML tag, including an image, and extracted the text content.

My favorite for my applications is using a regex match. It’s a cleaner solution, and I trust my inputs to be valid HTML.

const original = `

Welcome to my blog

Some more content here


`
; const regex = original.replace(/[^>]*>/g, ''); console.log(regex);
'Welcome to my blog Some more content here'

As you can see, we removed the heading, paragraph, break, and image. This is because we escape all HTML brackets with < >format.

It could be breached by something silly like:

const original = `

Welcome to my blog

Some more content here


a >2`
;

I know it’s not valid HTML anyhow, and one should use > for this.

But running this will result in:

'Welcome to my blog Some more content here 2" src="https://daily-dev-tips.com/posts/javascript-removing-html-tags/%3C/span%3E%3Cspan%20style=color:#c9d1d9%3Eimg.jpg%3C/span%3E%3Cspan%20style=color:#a5d6ff%3E" />'

It’s just something to be aware of.

You can try out the code of both methods in this Codepen:

See the Pen Exyqbqa by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Источник

How to clear all the input in HTML forms?

Using HTML forms, you can easily take user input. The tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.

The tag, helps you to take user input using the type attribute. To clear all the input in an HTML form, use the tag with the type attribute as reset.

Example 1

The following example demonstrates how to clear all the input in HTML forms.

In this example, we are going to use the document.getElementId to clear the text in the text field.

DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> meta http-equiv="X-UA-Compatible" content="IE=edge" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>Remove HTMLtitle> head> body> form> input type="button" value="click here to clear" onclick="document.getElementById('inputText').value = '' "/> input type="text" value="Tutorix" id="inputText" /> form> body> html>

When we click on the clear button the text inside the input(text area) field gets cleared.

Example 2

The following example demonstrates how to clear all the input in HTML forms.

In this example, we are going to use the rest button to clear the text in the text field.

DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> meta http-equiv="X-UA-Compatible" content="IE=edge" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>Clear all the input in HTML formstitle> head> body> form> input type="text" name="input" /> input type="reset" value="reset" /> form> body> html>

When we click on the clear button the text inside the input(text area) field gets cleared.

Example 3

The following example demonstrates how to clear all the input in HTML forms.

In this example, we are going to use onclick() method to clear the text in the text field.

DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> meta http-equiv="X-UA-Compatible" content="IE=edge" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>Clear all the input in HTML formstitle> head> body> form> input type="text" value="Tutorix is the best e-learning platform" onclick="this.value=''"/> form> body> html>

Example 4

You can try to run the following code to clear all the input in HTML forms −

DOCTYPE html> html> body> form> Student Name:br> input type="text" name="sname"> br> Student Subject:br> input type="text" name="ssubject"> br> input type="reset" value="reset"> form> body> html>

Once the reset button is clicked, the form is cleared.

Источник

Оцените статью