JavaScript Regular expression: matches all HTML tags

Source: Internet
Author: User

In the course of the interview encountered a topic such as:

For example, there is an HTML string:

var string= ' <div class ' test ' >test a code</div><em>i am a girl.</em> '; Requires writing a regular expression that matches the HTML tag, and replaces all tags.

The HTML tag has

In fact, the regular expression matching HTML tags is very short, as follows:

<[^>]+>

That's it, it's gone? Yes. Are you surprised?

This regular expression is also collected in the network, but I can understand, first of all, the HTML tag is definitely starting with the < symbol, the end of the > symbol (whether it is not self-closing), just a little tangled in the middle, there may be characters, numbers, quotes, newline characters--but, but there is no; Because of it, the HTML tag ends, so the middle of the regular expression is [^>]+, which means " any more than 1 characters apart from the > Symbol ".

Examples are as follows:

var string= '<class ' test '>test a code</div> <em>I am a girl. </ em >';

Regular:

var reg=/<[^>]+>/gim;

Output:
Test a Codei am a girl.


JavaScript Regular expression: matches all HTML tags

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.