*我已經搜查堆棧溢出,並試圖回答所有的類似的問題*的Javascript正則表達式得到的類名
我正在寫一個節點腳本:
- 掃描目錄HTML文件
- 讀取文件內容爲一個字符串
- 搜索的字符串ID或類名
我正在使用正則表達式來查找id或類的名稱。當我搜索一個id時,我可以得到一個匹配,但是當我搜索一個類名時不能。
赫雷什我的例子的代碼:
爲了簡單起見,我把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));
看一看http://stackoverflow.com/questions/16559171/regular-expression-to- get-a-class-name-from-html – psycho
沒有任何關於該主題的解決方案適用於我。 –
你能否添加一些關於什麼是失敗的細節?預期產出應該是什麼樣子,它看起來是什麼樣的?你的代碼在哪一點失敗?'(class | id)=「(。*?)」'? – nozzleman