This is an example.
This is another examp...">

How to clear tags from a string using JavaScript

<div id="mydiv"> <p> <b><a href="mypage.html">This is an example<a>.</b> <br> This is another example. </p> </div> <script type="text/javascript"> var mystr = document.getElementById('mydiv').innerHTML; ..... </script> 

I want to clear all the tags and get the salt text,

 mystr = "This is an example this is another example."; 

How can i do this?

+4
source share
4 answers

Using innerText and textContent :

 var element = document.getElementById('mydiv'); var mystr = element.innerText || element.textContent; 

Demo

I only saw that the string would still contain line breaks. You can remove them with replace :

 mystr = mystr.replace(/\n/g, ""); 

Update:

As @ Ε ime Vidas points out in his comment, it seems that you need to handle spaces a little differently to fix the line in IE:

 mystr = mystr.replace(/\s+/g, ' '); 
+10
source

Here's another approach - remove tags using replace with regex:

 document.getElementById('mydiv').innerHTML.replace(/\n|<.*?>/g,'') 

Here is the fiddle

+2
source

Try:

 document.getElementById('mydiv').innerText || document.getElementById('mydiv').textContent; 
+1
source

You can scroll through all the children and read .innerText from them. Then you can easily concatenate the text from each child element and get all the text without tags.

0
source

Source: https://habr.com/ru/post/1338430/


All Articles