SoFunction
Updated on 2025-03-02

Use regular expression to remove all html tags and keep only text

If the backend returns the content in the rich text editor to the front end, you can use this method to retain only the text.

There are several formats for labels

1.<div class="test"></div>

2.<img />

3. Custom tags<My-Tag></My-Tag>

For the above tags, the regular rules determined are reg=/<\/?.+?\/?>/g

<Denote angle brackets

The first \/? indicates the situation of this tag </div>

.+? means that everything in the middle is replaced

The second \/? means <img/>

/g means global replacement

The code is as follows:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;title&gt;Remove all tags&lt;/title&gt;
&lt;/head&gt;
&lt;script&gt;
  function matchReg(str){
    let reg=/&lt;\/?.+?\/?&gt;/g;
    ((reg,''));
  }
  matchReg(`&lt;p&gt;Remove allhtmlLabel,&lt;img/&gt;&lt;My-Tag class="abc" value="test"&gt;自定义Label也可以去除哦&lt;/My-Tag&gt;&lt;/p&gt;`);
&lt;/script&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;

Summarize

The above is what the editor introduced to you using regular expressions to remove all html tags and only retain text. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!