2017-02-10 26 views
0

*我已經搜查堆棧溢出,並試圖回答所有的類似的問題*的Javascript正則表達式得到的類名

我正在寫一個節點腳本:

  1. 掃描目錄HTML文件
  2. 讀取文件內容爲一個字符串
  3. 搜索的字符串ID或類名

我正在使用正則表達式來查找id或類的名稱。當我搜索一個id時,我可以得到一個匹配,但是當我搜索一個類名時不能。

赫雷什我的例子的代碼:

https://jsbin.com/bayuquzulu/edit?js,console

爲了簡單起見,我把HTML到一個變量,並省略文件讀取部。

var html = '<section class="mb-4" id="button-test">'+ 
     '<button type="button" class="btn btn-primary">Primary</button>'+ 
     '<button type="button" class="btn btn-secondary">Secondary</button>'+ 
     '<button type="button" class="btn btn-success">Success</button>'+ 
     '</section>'; 

var scan = function(content) { 

    var props = ['btn-primary', 'button-test'], res = {}; 

    for (var i = 0; i < props.length; i++) { 
     var prop = props[i]; 

     var exps = [ 
      {key: '#', exp: new RegExp("<*.* id=([\"]|')\\s*"+prop+"\\s*([\"]|').*>", "gi")}, 
      {key: 'data-comp=', exp: new RegExp("<*.* data-dna=([\"]|')\\s*"+prop+"\\s*([\"]|').*>", "gi")}, 
      {key: '.', exp: new RegExp("<*.* class=([\"]|')*."+prop+".*([\"]|').*>", "gi")} 
     ]; 

     for (var e = 0; e < exps.length; e++) { 
      var item = exps[e]; 
      var key = item.key; 
      var exp = item.exp; 
      var match = content.match(exp); 

      key += prop; 

      if (match) { 

       if (!res[key]) { res[key] = []; } 

       res[key].push(match[0]); 

      } 
     } 
    } 

    return res; 
} 

console.log(scan(html)); 
+0

看一看http://stackoverflow.com/questions/16559171/regular-expression-to- get-a-class-name-from-html – psycho

+0

沒有任何關於該主題的解決方案適用於我。 –

+0

你能否添加一些關於什麼是失敗的細節?預期產出應該是什麼樣子,它看起來是什麼樣的?你的代碼在哪一點失敗?'(class | id)=「(。*?)」'? – nozzleman

回答

1

我認爲這可能是答案:

const data = `<section class="mb-4" id="button-test"> 
 
    <button type="button" class="btn btn-primary">Primary</button> 
 
    <button type="button" class="btn btn-secondary"> 
 
     Secondary 
 
    </button> 
 
    <button type="button" class="btn btn-success"> 
 
     Success 
 
    </button> 
 
</section>` 
 

 
const elements = [] 
 

 
const findTag = /<[^\/].*?>/g 
 
let element 
 
while(element = findTag.exec(data)){ 
 
    element = element[0] 
 
    const id = (element.match(/id="(.*?)"/i) || [, ""])[1] 
 
    const classes = (element.match(/class="(.*?)"/i) || [,""])[1].split(' ') 
 
    
 
    element = {} 
 
    element["id"] = id 
 
    element["class"] = classes 
 
    elements.push(element) 
 
} 
 
console.log("All elements") 
 
console.log(elements) 
 

 
// You can now also filter elements 
 
console.log("All elements having btn class")  
 
console.log(elements.filter(element => element.class.indexOf("btn") != -1))

+0

啊,我沒有想到首先創建標籤解析器。謝啦! –

+0

解決一個大問題的最好方法是將它分成幾個較小的問題:D –