Strip HTML from Text JavaScript

前端 未结 30 3577
北荒
北荒 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:32

    A lot of people have answered this already, but I thought it might be useful to share the function I wrote that strips HTML tags from a string but allows you to include an array of tags that you do not want stripped. It's pretty short and has been working nicely for me.

    function removeTags(string, array){
      return array ? string.split("<").filter(function(val){ return f(array, val); }).map(function(val){ return f(array, val); }).join("") : string.split("<").map(function(d){ return d.split(">").pop(); }).join("");
      function f(array, value){
        return array.map(function(d){ return value.includes(d + ">"); }).indexOf(true) != -1 ? "<" + value : value.split(">")[1];
      }
    }
    
    var x = "Hello world!";
    console.log(removeTags(x)); // Hello world!
    console.log(removeTags(x, ["span", "i"])); // Hello world!
    

提交回复
热议问题