Remove specific HTML tag with its content from javascript string

Asked
Active3 hr before
Viewed126 times

9 Answers

stringremovespecific
90%

How to strip out HTML tags from a string using JavaScript ?,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. HTML tags are of two types opening tag and closing tag.,How to remove text from a string in JavaScript?,How to remove a character from string in JavaScript ?

load more v
88%

I have the following string variable and I want to remove all a tags with its content from the string.,I have checked this Remove HTML content groups from start to end of string in JavaScript question's answers but it is for all tags.,Find centralized, trusted content and collaborate around the technologies you use most., 1 @Bangkokian 10 years old question! but the answers in this thread are still relevant IMO: stackoverflow.com/q/590747 . – Ravimallya Aug 22 at 3:48

// your HTML text
var 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 container
var div = document.createElement('div');

// assing your HTML to div's innerHTML
div.innerHTML = myString;

// get all <a> elements from div
   var elements = div.getElementsByTagName('a');

   // remove all <a> elements
      while (elements[0])
      elements[0].parentNode.removeChild(elements[0])

      // get div's innerHTML into a new variable
      var repl = div.innerHTML;

      // display it
      console.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>
      */
load more v
72%

//remove html tags from a string, leaving only the inner text
function removeHTML(str){ 
    var tmp = document.createElement("DIV");
    tmp.innerHTML = str;
    return tmp.textContent || tmp.innerText || "";
}
var html = "<div>Yo Yo Ma!</div>";
var onlyText = removeHTML(html); "Yo Yo Ma!"
65%

I recently needed to remove all HTML tags from text content of my own application to return the clean text.,As you can see we removed every HTML tag including an image and extracted the text content.,One method is to create a temporary HTML element and get the innerText from it.,My personal favourite for my own applications is using a regex match. It's just a cleaner solution and I trust my own inputs to be valid HTML.

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

const original = `<h1>Welcome to my blog</h1><p>Some more content here</p><br /><img alt="a > 2" src="img.jpg" />`;let removeHTML = input => {	let tmp = document.createElement('div');	tmp.innerHTML = input;	return tmp.textContent || tmp.innerText || '';} console.log(removeHTML(original));
load more v
75%

Directly extract the text content from an HTML element – var txt = ELEMENT.textContent; ,Use regular expression – var txt = HTML-STRING.replace(/(&lt;([^>]+)>)/gi, ""); ,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. ,Use the DOM parser then extract the text content – var dom = new DOMParser().parseFromString(HTML-STRING, 'text/html'); var txt = dom.body.textContent;

 // (A) STRIP TAGS FUNCTION
function stripTags (original) {
  return original.replace(/(<([^>]+)>)/gi, "");
}
 
// (B) ORIGINAL STRING
 var str = "<p>This is a <strong>string</strong> with some <u>HTML</u> in it.</p>";
 
// (C) "CLEANED" STRING
var cleaned = stripTags(str);
console.log(cleaned);
load more v
40%

If for some reason (like malicious intent of users) the html argument contains a script tag, you’ve now opened up for XSS attacks!!!, Morgan Roderick Permalink to comment# March 28, 2013 That is awful advice! If for some reason (like malicious intent of users) the html argument contains a script tag, you’ve now opened up for XSS attacks!!! Don’t use the DOM for something that doesn’t require it. Also, the DOM is really slow. ,Hi guys! I am currently facing a javascript problem with the regex / replace function you mention here. I would like to bring a text around some of its HTML tags.,I saw your contact form and i must say i love it! Do you have a tutorial or something like that? It’s a wonderful one :)^ Hope to hear some news of you,

let strippedString = originalString.replace(/(<([^>]+)>)/gi, "");
load more v
22%

strip_tags — Strip HTML and PHP tags from a string, This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given string. It uses the same tag stripping state machine as the fgetss() function. , This function should not be used to try to prevent XSS attacks. Use more appropriate functions like htmlspecialchars() or other means depending on the context of the output. , HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowed_tags.

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
60%

We can remove HTML/XML tags in a string using regular expressions in javascript. HTML elements such as span, div etc. are present between left and right arrows for instance <div>,<span> etc. So replacing the content within the arrows, along with the arrows, with nothing('') can make our task easy.,How to remove the HTML tags from a given string in Java?,Remove characters from a string contained in another string with JavaScript?,How to remove text from a string in JavaScript?

Syntax

str.replace(/(<([^>]+)>)/ig, '');
load more v
48%

The only problem of this (and the advantage) is that the browser will handle the providen string as HTML, that means that if the HTML string contains some type of interpretable Javascript for the browser, then it will be executed:,This is the preferred (and recommended) way to strip the HTML from a string with Javascript. The content of a temporary div element, will be the providen HTML string to strip, then from the div element return the innerText property:,Therefore, you should use this only if you trust the source of the HTML string.,If you're working in a Node environment, where there's not either document or createElement method, then you can use a regular expression to replace all the HTML tags from a string:

This is the preferred (and recommended) way to strip the HTML from a string with Javascript. The content of a temporary div element, will be the providen HTML string to strip, then from the div element return the innerText property:

/**
 * Returns the text from a HTML string
 * 
 * @param {html} String The html string
 */
function stripHtml(html){
    // Create a new div element
    var temporalDivElement = document.createElement("div");
    // Set the HTML content with the providen
    temporalDivElement.innerHTML = html;
    // Retrieve the text property of the element (cross-browser support)
    return temporalDivElement.textContent || temporalDivElement.innerText || "";
}

var htmlString= "<div><h1>Hello World</h1>\n<p>It's me, Mario</p></div>";

//Hello World
//It's me, Mario
console.log(stripHtml(htmlString));
load more v

Other "string-remove" queries related to "Remove specific HTML tag with its content from javascript string"