JS中的Preg_match

时间:2016-09-18 22:20:00

标签: javascript web-scraping preg-match

HTML代码

    <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>

如何在js中提取/admin/orders/restart/id/163148/admin/orders/restart/id/162616?我需要把它放在一个数组中。

我对preg_match并不擅长。如何使用js提取/ admin / orders / restart / id / 163148和/ admin / orders / restart / id / 162616

1 个答案:

答案 0 :(得分:1)

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

或者,添加了绒毛:

&#13;
&#13;
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 );
&#13;
<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>
&#13;
&#13;
&#13;