Deep Frozen
Deep Frozen

Reputation: 2075

Javascript regex not working as intended

I have the HTML from a page in a variable as just plain text. Now I need to remove some parts of the text. This is a part of the HTML that I need to change:

<div class="post"><a name="6188729"></a>
    <div class="igmline small" style="height: 20px; padding-top: 1px;">
        <span class="postheader_left">
            <a href="#"  style="font-size:9pt;"> RuneRifle </a>
            op 24.08.2012 om 21:41 uur
        </span>
        <span class="postheader_right">
            <a href="http://link">Citaat</a> <a href="http://link">Bewerken</a>
        </span>
        <div style="clear:both;"></div>
    </div>
    <div class="text">Testforum</div>
    <!-- Begin Thank -->
    <!-- Thank End -->
</div>

These replaces work:

pageData = pageData.replace(/href=\".*?\"/g, "href=\"#\"");
pageData = pageData.replace(/target=\".*?\"/g, "");

But this replace does not work at all:

pageData = pageData.replace(
  /<span class=\"postheader_right\">(.*?)<\/span>/g, "");

I need to remove every span with the class postheader_right and everything in it, but it just doesn't work. My knowledge of regex isn't that great so I'd appreciate if you would tell me how you came to your answer and a small explanation of how it works.

Upvotes: 1

Views: 120

Answers (2)

Brett Zamir
Brett Zamir

Reputation: 14365

The dot doesn't match newlines. Use [\s\S] instead of the dot as it will match all whitespace characters or non-whitespace characters (i.e., anything).

As Mike Samuel says regular expressions are not really the best way to go given the complexity allowed in HTML (e.g., if say there is a line break after <a), especially if you have to look for attributes which may occur in different orders, but that's the way you can do it to match the case in your example HTML.

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120576

I need to remove every span with the class postheader_right and everything in it, but it just doesn't work.

Don't use regular expressions to find the spans. Using regular expressions to parse HTML: why not?

var allSpans = document.getElementsByClassName('span');
for (var i = allSpans.length; --i >= 0;) {
  var span = allSpans[i];
  if (/\bpostheader_right\b/.test(span.className)) {
    span.parentNode.removeChild(span);
  }
}

should do it.

If you only need to work on newer browsers then getElementsByClassName makes it even easier:

Find all div elements that have a class of 'test'

var tests = Array.filter( document.getElementsByClassName('test'), function(elem){
  return elem.nodeName == 'DIV';
});

Upvotes: 1

Related Questions