KAZ-to-USA KAZ-to-USA - 3 months ago 13
Javascript Question

Regex help - include, but not show

I have a

this.responseText
, which is messy. Trying to separate the ones that I need:

Here's the text:

<html>
<head><title>Index of /browserify-view/build/source/pic/</title></head>
<body bgcolor="white">
<h1>Index of /browserify-view/build/source/pic/</h1><hr><pre><a href="../">../</a>
<a href="wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png">wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc..&gt;</a> 22-Jul-2016 22:29 65180
<a href="thumb-wd20f381801bb51.png">thumb-wd20f381801bb51.png;</a> 22-Jul-2016 22:33 10779
</pre><hr></body>
</html>


How can I separate like this:

wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png

thumb-wd20f381801bb51.png

Answer

First of all, DO NOT do this with Regex!

Regex is NOT capable of parsing HTML!


Use the javascript DOMParser instead:

var parser = new DOMParser();
var doc = parser.parseFromString(this.responseText, 'text/html');

Then use the DOM API to get the elements you need:

var nodes = doc.querySelectorAll('a:not([href="../"])');

And finally, use Array.map to map the nodes to their href attributes:

// Can't use nodes.map here because nodes in a NodeList, not an array
var links = Array.prototype.map.call(nodes, function(element)
{
    // Can't use element.href here because we're in a different document
    return element.getAttribute('href');
});

If you put that all together:

var exampleResponseText = `<html>
<head><title>Index of /browserify-view/build/source/pic/</title></head>
<body bgcolor="white">
<h1>Index of /browserify-view/build/source/pic/</h1><hr><pre><a href="../">../</a>
<a href="wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png">wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc..&gt;</a> 22-Jul-2016 22:29               65180
<a href="thumb-wd20f381801bb51.png">thumb-wd20f381801bb51.png;</a> 22-Jul-2016 22:33               10779
</pre><hr></body>
</html>`;

var parser = new DOMParser();
var doc = parser.parseFromString(exampleResponseText, 'text/html');
var nodes = doc.querySelectorAll('a:not([href="../"])');
var links = Array.prototype.map.call(nodes, function(element)
{
    return element.getAttribute('href');
});

console.log(links);