How to clear tags from a string with JavaScript

11,916

Solution 1

Using innerText and textContent:

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

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, ' ');

Solution 2

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

Solution 3

Try:

document.getElementById('mydiv').innerText || document.getElementById('mydiv').textContent;
Share:
11,916
Okan Kocyigit
Author by

Okan Kocyigit

https://bitbucket.org/ocanal/ https://github.com/okankocyigit Email: hasanokan[at]gmail[dot]com

Updated on June 14, 2022

Comments

  • Okan Kocyigit
    Okan Kocyigit almost 2 years
    <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?

  • Šime Vidas
    Šime Vidas about 13 years
    The replace() will only replace one line-break - see here: jsfiddle.net/yPj3a/4
  • Felix Kling
    Felix Kling about 13 years
    @Sime: Ah right... I forgot that JavaScript's replace method works.... differently ;) Thanks and fixed.
  • Šime Vidas
    Šime Vidas about 13 years
    replace(/\n/g, '') has browser compatibility issues. This: replace(/\s+/g, ' ') works cross-browser, see here: jsfiddle.net/yPj3a/8
  • Felix Kling
    Felix Kling about 13 years
    @Sime: Thanks :) (I have no IE to test though...)
  • Šime Vidas
    Šime Vidas about 13 years
    From my testing \s+ will catch all white-space including line breaks which makes it the ultimate solution. \n is therefore not needed.