Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear tags from a string with 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 tags, and get the salt text,

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

How can I do that?

like image 564
Okan Kocyigit Avatar asked Dec 09 '22 11:12

Okan Kocyigit


2 Answers

Using innerText and textContent:

var element = document.getElementById('mydiv');
var mystr = element.innerText || element.textContent;
  • innerText is supported by all browsers but FF
  • textContent is supported by all browsers but IE

DEMO

I just saw that the string will still contain line breaks. You might want to remove them with replace:

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

Update:

As @Šime Vidas points out in his comment, it seems you have to handle the whites spaces a bit differently to fix the string in IE:

mystr = mystr.replace(/\s+/g, ' ');
like image 153
Felix Kling Avatar answered Dec 26 '22 14:12

Felix Kling


Here is a different approach - remove the tags using replace with a regular expression:

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

Here is a fiddle

like image 30
Mike C Avatar answered Dec 26 '22 14:12

Mike C