Search code examples
javascriptweb-scrapingpreg-match

Preg_match in JS


HTML code

    <li class="btn-xs"><a tabindex="-1" 
    href="/admin/orders/restart/id/163148"   
    >Restart</a></li>
    <li class="btn-xs" style="display:none;"><a tabindex="-1" href="" data-
    toggle="modal" data-target="#check_alls_163148_s" 
    style="cursor:pointer;">Set&nbsp;start&nbsp;count</a></li>
    <li class="btn-xs"><a tabindex="-1" 
    href="/admin/orders/restart/id/162616">Restart</a></li>
    <li class="btn-xs" style="display:none;"><a tabindex="-1" href="" data-
    toggle="modal" data-target="#check_alls_162616_s" 
    style="cursor:pointer;">Set&nbsp;start&nbsp;count</a></li>

How can I extract /admin/orders/restart/id/163148 and /admin/orders/restart/id/162616 in js? I need to put it in an array.

I'm not good with preg_match. How can i extract /admin/orders/restart/id/163148 and /admin/orders/restart/id/162616 using js


Solution

  • Array.prototype.slice.call(document.querySelectorAll('li.btn-xs a'))
                   .map( a => a.getAttribute("href") )
                   .filter( href => href && href.length > 0 )
    

    Or, with added fluff:

    function selectByNonBlank() {
        return Array.prototype.slice.call(document.querySelectorAll('li.btn-xs a')).map( a => a.getAttribute("href") ).filter( a => a && a.length > 0 );
    }
    
    function selectByRestart() {
        return Array.prototype.slice.call(document.querySelectorAll('li.btn-xs a')).filter( a => a.innerHTML == "Restart" ).map( a => a.getAttribute("href") );
    }
    
    function init() {
      document.getElementById("restart").addEventListener("click", function() { console.log(selectByRestart()); });
    document.getElementById("href").addEventListener("click", function() { console.log(selectByNonBlank()); });
    }
    
    document.addEventListener( "DOMContentLoaded", init, false );
    <li class="btn-xs"><a tabindex="-1" href="/admin/orders/restart/id/163148"   >Restart</a></li>
    <li class="btn-xs" style="display:none;"><a tabindex="-1" href="" data-toggle="modal" data-target="#check_alls_163148_s" style="cursor:pointer;">Set&nbsp;start&nbsp;count</a></li>
    <li class="btn-xs"><a tabindex="-1" href="/admin/orders/restart/id/162616"   >Restart</a></li>
                  <li class="btn-xs" style="display:none;"><a tabindex="-1" href="" data-toggle="modal" data-target="#check_alls_162616_s" style="cursor:pointer;">Set&nbsp;start&nbsp;count</a></li>
    <button id="restart">Select by Restart</button>
    <button id="href">Select by non blank href</button>