Search code examples
javascriptstrip-tags

Equivalent strip_tags of PHP in javascript with allowed tags


I used this code to strip all tags but I wan't to save some tags like <img> and so on... How can I do? I can't understand how can I filter tags

/***************************************************
    STRIP HTML TAGS
    ****************************************************/
    function strip_tags(html){
 
        //PROCESS STRING
        if(arguments.length < 3) {
            html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
        } else {
            var allowed = arguments[1];
            var specified = eval("["+arguments[2]+"]");
            if(allowed){
                var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
                html=html.replace(new RegExp(regex, 'gi'), '');
            } else{
                var regex='</?(' + specified.join('|') + ')\b[^>]*>';
                html=html.replace(new RegExp(regex, 'gi'), '');
            }
        }
 
        //CHANGE NAME TO CLEAN JUST BECAUSE 
        var clean_string = html;
 
        //RETURN THE CLEAN STRING
        return clean_string;

EDIT** This is my HTML code

<body class="portrait" onLoad="prepareImages()">
    <div id="title_wrapper"><h2 id="title"><a href="[[[LINK]]]">[[[TITLE]]]</a></h2></div>
    <h2 id="subtitle">[[[DATE]]]</h2>
     <div id="content">
        [[[FULL CONTENT]]] etc....
    </div>

I used your function in this way (what I must replace is the: [[[FULL CONTENT]]] etc....)

(strip_tags(contentElem,"<img>");

without results. How can I rewrite the [[[FULL CONTENT]]] etc.... with the [[[FULL CONTENT]]] etc.... without html tags except <img> ?


Solution

  • Eval? Ugh, that is really ugly code. It matches all tags by using a regular expression pattern.

    • If the function call has less than 3 parameters, it just strips all tags.
    • If the function call has at least 3 parameters:
      • The third parameter is a string like "a", "b", "strong". The quotes are required, thanks to the ugly evil eval construct.
      • if the second parameter is a truth-value (true for example), the third parameter is the list of tags that are allowed
      • if the second parameter is a false-value (false for example), the third parameter is the list of tags that are denied

    If you need a proper strip_tags function, have a look at http://phpjs.org/functions/strip_tags:535