Saturday, October 25, 2025
HomeLanguagesJavascriptHow to remove HTML tags with RegExp in JavaScript ?

How to remove HTML tags with RegExp in JavaScript ?

Here, the task is to remove the HTML tags from the string. Here string contains a part of the document and we need to extract only the text part from it. Here we are going to do that with the help of JavaScript. 

Approach:

  • Take the string in a variable.
  • Anything between the less than symbol and the greater than symbol is removed from the string by the RegExp.
  • Finally, we will get the text.

Example 1: This example using the approach defined above. 

html




<h1 style="color:green;">
    neveropen
</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN"></p>
<script>
    var up = document.getElementById('GFG_UP');
    var str2 = '<p> GeeksForGeeks </p>';
      
    // same as the str2.
    var str1 = "< p > GeeksForGeeks < /p >";
    up.innerHTML = "Click on button to remove the "+
    "HTML tags from the string.<br>String = '" + str1 + "'";
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        var regex = /(|<([^>]+)>)/ig;
        down.innerHTML = str2.replace(regex, "");
    }
</script>


Output:

How to remove HTML tags with RegExp in JavaScript?

How to remove HTML tags with RegExp in JavaScript?

Example 2: This example uses the approach defined above but by a different RegExp. 

html




<h1 style="color:green;">
    neveropen
</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN"></p>
<script>
    var up = document.getElementById('GFG_UP');
    var str2 = '<p> GeeksForGeeks </p>';
      
    // same as the str2.
    var str1 = "< p > GeeksForGeeks < /p >";
    up.innerHTML = "Click on button to remove the HTML"+
    " tags from the string.<br>String = '" + str1 + "'";
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        var regex = /(<([^>]+)>)/ig;
        down.innerHTML = str2.replace(regex, "");
    }
</script>


Output:

How to remove HTML tags with RegExp in JavaScript?

How to remove HTML tags with RegExp in JavaScript?

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS