使用 cheerio 使用正则表达式获取属性

using cheerio to get attributes using a regex

我想使用模式获取标签的属性。考虑这样的事情

<foo id="136E2A751268FFDFD3EB6CB6FE91D88F" 
    captionText-0="bla bla" 
    captionText-1="bada bing bada boom" 
    httpUri-0="https://path/to/server0" 
    httpUri-1="https://path/to/server2">foo 1-2</foo>

使用 cheeriojs,类似下面的东西(当然,这不起作用)

const attribs = [
    'captionText',
    'httpUri'
]

const tag = {}
attribs.forEach(a => {
    const re = `${a}-[0-9]+`
    const attr = $(e).attr(/re/)
    if (attr) {
        tag[re] = attr
    }
})

建议?

如果您只是简单地匹配一个列表,那么:

// cheeiro output of element.attribs
var attribs = {
  'captionText-1': '1',
  'captionText-2': '2',
  'httpUri-3': 3,
  'httpUri-4': 4
};
// list of values to match against
var match_list = ['captionText', 'httpUri'];
// holds matched key/value attributes
var tag = {};
// loops through attribs object
for (var key in attribs) {
  // returns boolean, partial matches current attribute against each value in match list
  // var is_matched = match_list.some(function(item) {return key.indexOf(item) > -1;});
  var is_matched = match_list.some(function(item) {return key.match(new RegExp('^' + item + '-[0-9]+', 'gi'));});
  if (is_matched) {
    tag[key] = attribs[key];
  }
}