Improve your skills

August 23, 2016

Remove all HTML Tags from a string in jQuery using Regular Expression (Regex)


In this article, we discuss about how to remove or strip all HTML tags or elements in jQuery/JavaScript using Regular Expression (Regex). 

It means, if we pass "<span style='testStyle'> test string </span>" string to the function. Then the function return only simple text between tags "test string".
Note: It also works, if sting contains &nbsp; . 


Example:
Input String:
<div class="text-note note">
<p style='color:green;'>A JavaScript string simply stores a series of characters.</p>
<p>Please don't create strings as objects. It slows down execution speed of web page.<br>
The <strong>new</strong> keyword complicates the code. This can produce some unexpected results.</p>
</div>

Output String:
A JavaScript string simply stores a series of characters. 
Please don't create strings as objects. It slows down execution speed of web page. 
The  new  keyword complicates the code. This can produce some unexpected results.

Description: textContent(the DOM standard property) and innerText(non-standard) properties are not identical. For example, textContent will include text with in a <script>
element while innerText will not (in most browsers). This only affects IE<=8, which is the only major browser not support textContent. 

First, we take a input text or textarea and a input button in body as show in below-

HTML:
<body style="background: #E0EDFA; text-align: center; margin-top: 250px;">
<form id="form1">
<textarea id="txtHtmlString" rows="5" cols="50"></textarea><br />
<input id="btnRemoveHtmlTags" type="button" value="Remove All Html Tags"     onclick="getHtmlFreeText();" />
</form>
</body>

After that, attach the jquery library link on your head part of page and write the below javascript code in head part as shown below-

JS:
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        function getHtmlFreeText() {
            var htmlStr = $('#txtHtmlString').val();
            htmlStr = htmlStr.split(">").join("> ").trim();
            var newDiv = document.createElement("DIV");
            newDiv.innerHTML = htmlStr;
            var simpleText = newDiv.textContent || newDiv.innerText || "";
            $('#txtHtmlString').val(simpleText);
        }

    </script>
</head>

Now save the file and run on browser.

After write HTML content on textarea, click on 'Remove All Html Tags' button. Then all the HTML tags, style, class are removed and simple text content visible on the textarea.

Result:
Strip or Remove all HTML Tags or Elements From a String in jquery Using Regular Expression












Live Demo:





0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts