strip_tags

by Greggg

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.6.20/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.6.20/js/uikit-icons.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.6.20/css/uikit.min.css">

JavaScript

var text= '<div data-uk-responsive id="text"><h1>Title</h1><p><span>test</span><span data-uk-icon="icon: plus; ratio: 2">retest</span><p><ul><li data-animal-type="bird">Owl</li></ul><p name="any name Test 1234" ID="test" class="test test2  test3" style="color:red; margin: 10px;"> paragraph </p><div style="color:red"> div which should be stripped<p style="color:red; line-height: 1.365; margin-top: 0pt; margin-bottom: 12pt;"> paragraph </p></div><strong style="color:red"> strong which should be stripped </strong></div>';

document.write(strip_tags(text, '<p>'));

function strip_tags (input, allowed) {

    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    		clearAttributes = /[a-z0-9]*="[a-z0-9-.:; ]*"/gi,
        // clearStyle = /style="([^"]*)"/gi
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input
.replace(commentsAndPhpTags, '')
.replace(clearAttributes, '')
// .replace(clearStyle, '')
.replace(tags, function ($0, $1){
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}