Strip HTML from Text JavaScript

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

    input element support only one line text:

    The text state represents a one line plain text edit control for the element's value.

    function stripHtml(str) {
      var tmp = document.createElement('input');
      tmp.value = str;
      return tmp.value;
    }
    

    Update: this works as expected

    function stripHtml(str) {
      // Remove some tags
      str = str.replace(/<[^>]+>/gim, '');
    
      // Remove BB code
      str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2 ');
    
      // Remove html and line breaks
      const div = document.createElement('div');
      div.innerHTML = str;
    
      const input = document.createElement('input');
      input.value = div.textContent || div.innerText || '';
    
      return input.value;
    }
    

提交回复
热议问题