Strip HTML from Text JavaScript

前端 未结 30 4129
北荒
北荒 2020-11-21 05:08

Is there an easy way to take a string of html in JavaScript and strip out the html?

30条回答
  •  無奈伤痛
    2020-11-21 05:27

    function stripHTML(my_string){
        var charArr   = my_string.split(''),
            resultArr = [],
            htmlZone  = 0,
            quoteZone = 0;
        for( x=0; x < charArr.length; x++ ){
         switch( charArr[x] + htmlZone + quoteZone ){
           case "<00" : htmlZone  = 1;break;
           case ">10" : htmlZone  = 0;resultArr.push(' ');break;
           case '"10' : quoteZone = 1;break;
           case "'10" : quoteZone = 2;break;
           case '"11' : 
           case "'12" : quoteZone = 0;break;
           default    : if(!htmlZone){ resultArr.push(charArr[x]); }
         }
        }
        return resultArr.join('');
    }
    

    Accounts for > inside attributes and in newly created dom elements.

    usage:

    clean_string = stripHTML("string with  in it")
    

    demo:

    https://jsfiddle.net/gaby_de_wilde/pqayphzd/

    demo of top answer doing the terrible things:

    https://jsfiddle.net/gaby_de_wilde/6f0jymL6/1/

提交回复
热议问题