简体   繁体   中英

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.

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

As Mike Samuel says regular expressions are not really the best way to go given the complexity allowed in HTML (eg, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM