-2

Given:

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));
});

if I do:

console.log(newtext);

I get:

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

So we do have a match for United Kingdom yet when I run console.log(newtext.match(regex)); the console gives me null null null...

I am looking for a match of a string against the strings in the array and if there is a match, output that match in the console. In this case it'd be United Kingdom

Here it is a jsFiddle

rob.m
  • 9,843
  • 19
  • 73
  • 162
  • What output are you looking for? – Matt Aug 01 '17 at 15:15
  • @mkaatman I am looking for the console to give me `United Kingdom` as that is the correct match – rob.m Aug 01 '17 at 15:15
  • I have no idea what your asking here? – Liam Aug 01 '17 at 15:17
  • @Liam I am looking for a match of a string against the strings in the array and if there is a match, output that match in the console – rob.m Aug 01 '17 at 15:18
  • why the down votes? – rob.m Aug 01 '17 at 15:20
  • Possible duplicate of [How to search for a string inside an array of strings](https://stackoverflow.com/questions/5424488/how-to-search-for-a-string-inside-an-array-of-strings) – Liam Aug 01 '17 at 15:25
  • @Liam i was actually looking at this https://stackoverflow.com/a/13509693/1018804 but I don't understand why the code above isn't working tho, now trying the solution found on that link here – rob.m Aug 01 '17 at 15:26
  • @Liam `$wikiDOM.find(".infobox td div li a").each(function(){ var newtext = $(this).text(); for( var i = 0; i < countries.length; i++ ) { if ( countries[i] === newtext ) { console.log(newtext); } } });` but i get nothing in console, if i output countries which is the countries array, i get them all – rob.m Aug 01 '17 at 15:29
  • @Liam provided my own answer – rob.m Aug 01 '17 at 16:12
  • @mkaatman provided my own answer – rob.m Aug 01 '17 at 16:12

1 Answers1

0

The list i was getting via the .each() was indeed giving me United Kingdom which we have in the array, yet the html was United&nbsp;Kingdom therefore I did:

$wikiDOM.find(".infobox td div li a").each(function(){
  var newtext = $(this).html();
  var newtextStriped = newtext.replace(/&nbsp;/g,' ');
  if( $.inArray(newtextStriped, countries) != -1){
    console.log(newtextStriped);
  }
});
rob.m
  • 9,843
  • 19
  • 73
  • 162