remove html tags from string code example

Example 1: javascript strip html tags from string

var htmlString= "<div>\n <h1>Hello World</h1>\n <p>This is the text that we should get.</p>\n <p>Our Code World &#169; 2017</p>\n </div>";

var stripedHtml = htmlString.replace(/<[^>]+>/g, '');
var decodedStripedHtml = he.decode(stripedHtml);

// Hello World
// This is the text that we should get.
// Our Code World &#169; 2017
console.log(stripedHtml);

// Hello World
// This is the text that we should get.
// Our Code World © 2017
console.log(decodedStripedHtml);

Example 2: php strip tags

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
//Test paragraph. Other text

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
//<p>Test paragraph.</p> <a href="#fragment">Other text</a>
// as of PHP 7.4.0 the line above can be written as:
// echo strip_tags($text, ['p', 'a']);
?>

Example 3: javascript remove html from text

//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!"

Tags:

Php Example