【问题标题】:How to match a string within a .each?如何匹配.each 中的字符串?
【发布时间】:2017-08-01 15:14:02
【问题描述】:

给定:

var countries = ["Afghanistan", "United Kingdom", "Albania", "United Arab Emirates"];
var regex = new RegExp(countries.join("|"), "i");

$wikiDOM.find(".infobox td div li a").each(function(){
  var newtext = $(this).text();
  //console.log(newtext);
  console.log(newtext.match(regex));
});

如果我这样做:

console.log(newtext);

我明白了:

White
Asian
Black
Mixed
Arab
1]
United Kingdom
England and Wales
^
Legislative Grand Committee

所以我们确实匹配了United Kingdom,但是当我运行console.log(newtext.match(regex)); 时,控制台给了我null null null...

我正在寻找一个字符串与数组中的字符串的匹配项,如果有匹配项,则在控制台中输出匹配项。在这种情况下,它将是 United Kingdom

这里是jsFiddle

【问题讨论】:

  • 你在寻找什么输出?
  • @mkaatman 我正在寻找控制台给我United Kingdom,因为这是正确的匹配
  • 我不知道你在这里问什么?
  • @Liam 我正在寻找一个字符串与数组中的字符串的匹配项,如果有匹配项,则在控制台中输出匹配项
  • 为什么投反对票?

标签: javascript jquery


【解决方案1】:

我通过.each() 获得的列表确实给了我数组中的英国,但 html 是United Kingdom,因此我这样做了:

$wikiDOM.find(".infobox td div li a").each(function(){
  var newtext = $(this).html();
  var newtextStriped = newtext.replace(/ /g,' ');
  if( $.inArray(newtextStriped, countries) != -1){
    console.log(newtextStriped);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2012-03-20
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多