2

Given a whole text like:

var nation = "Piazza delle Medaglie d'Oro
40121 Bologna
Italy"

And a given array like:

 ["Afghanistan", "Italy", "Albania", "United Arab Emirates"]

How can we check that the word Italy within that whole text is in the array?

Following this SO answer this is what I tried, but I get False while instead Italy is present within the array

  var countries = [];
  $("#usp-custom-3 option").each(function() {
    var single = $(this).text();
    countries.push(single);
    var foundPresent = countries.includes("Piazza delle Medaglie d'Oro 40121 Bologna Italy");
    console.log(foundPresent); 
  });

JsFiddle here

rob.m
  • 9,843
  • 19
  • 73
  • 162

5 Answers5

5

If you check whenever you push to an array, its even much simpler, just check the pushed element:

const text = " I like Italy";
const nations=[];

function insert(single){
 if( text.includes(single) /*may format single, e.g. .trim() etc*/){
   alert("Nation in text!");
 }
 nations.push(single);
}

Run


If you still want to check the whole array everytime, a nested iteration may does it:

let countries = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
const text = " I like Italy";

let countriesInText = countries.filter( word => text.includes( word ) );
//["Italy"]

Run

Performance compared to Rajeshs answer

If you just care if or if not, may use .some() instead of .filter().

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • You're assuming a word in the array can't be *in* a word of the text. You can't skip the tokenization. Which means there's no reason to check the other way round. – Denys Séguret Jul 28 '17 at 11:20
  • I actually prefer this answer, cleaner and very readable. (+1) – Tez Wingfield Jul 28 '17 at 11:33
  • @Jonasw some dev's like results. Not fast, clean, readable code. I have that battle at work haha - So I end up writing code for "results" not for the latter. – Tez Wingfield Jul 28 '17 at 11:38
  • @denys Seguret 1) depends on the definition of *in text* 2) because theres no need to check the whole array based on OPs edit – Jonas Wilms Jul 28 '17 at 11:39
  • this one actually makes more sense to me, and since I am not great at regex and I need to be it faster and readable, I am accepting this one here. Also it uses `includes` which is what I was working on as per the code in my question – rob.m Jul 28 '17 at 11:44
  • yet what is the reason we're keeping this line here `var countriesInText`.. ? Lets make this answer just straight to the point of the question without abstract examples, as the last conditional should be simply put up with the strings vars in the first bit of code, no? – rob.m Jul 28 '17 at 11:46
  • @rob.m would you not want the value? == "countriesInText" – Tez Wingfield Jul 28 '17 at 11:48
  • I would need to simply say "Nation in text". I mean that is the bit that says true or false and i can carry on with the rest of the code i have here – rob.m Jul 28 '17 at 11:49
  • @Jonasw You can use this [JSPerf](https://jsperf.com/regex-vs-filter-for-text-search) as a reference for performance difference. – Rajesh Jul 28 '17 at 11:50
  • Yup. Just thought you can add it in answer for readers' reference as comment would be in collapsed state. – Rajesh Jul 28 '17 at 11:55
3

Since you need to search a string with words in an array, best option is to use a regex and use string.match(regex) to get the matched words.

var nation = `Piazza delle Medaglie d'Oro
40121 Bologna
Italy`;
//var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
var countries = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
var regex = new RegExp(countries.join("|"), "i");
console.log(nation.match(regex))
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • oh this is so elegant actually, i never think of using a regex, can't get my head around them but looks so nice here – rob.m Jul 28 '17 at 11:26
  • @rob.m the text you shown,have new lines.? Isn't it? – Alive to die - Anant Jul 28 '17 at 11:28
  • @rob.m Glad I could help. Remember, a well constructed question will always attract better solutions as the problem statement is well defined. Showing effort/code will also help users in pointing improvements/ good practices. So if possible, share them. – Rajesh Jul 28 '17 at 11:28
  • @AlivetoDie yes it does have them indeed :( – rob.m Jul 28 '17 at 11:28
  • 1
    @Rajesh will do man, usually do it just had a quick hit on the send button, thanks man – rob.m Jul 28 '17 at 11:29
  • @Rajesh Where is `m` flag ? – Hassan Imam Jul 28 '17 at 11:33
  • Guys I have not updated anything yet. `Alive to Die` made the string multiline but there was no need to use `m` flag. I'll update in sometime. Sorry for delay. Trying to come up with a testable use-case – Rajesh Jul 28 '17 at 11:37
  • I don't think there is a need for any flags. This will work – Rajesh Jul 28 '17 at 11:42
  • can we have a conditional on here? `If match than say YEAH`? – rob.m Jul 28 '17 at 12:57
  • `if(nation.match(regex)) { console.log("yeah"); }` – rob.m Jul 28 '17 at 12:59
  • 1
    @rob.m You can do `var matches =nation.match(regex); if(matches!=null && matches.length > 0) { ...}` or just `matches != null` will also suffice as it will return `null` if no match is found. – Rajesh Jul 28 '17 at 13:19
0
var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
searchStringInArray("Italy", nation);
function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
}
Ankur
  • 177
  • 3
  • 15
0

this script will compare every word from var nation with all elements of array that you provided. I hope that this will solve your issue

<script>
    var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
    test = nation.split(" ");
    array = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
    test.forEach(function (element) {
        array.forEach(function (array_to_compare) {
            if (element == array_to_compare)
                alert("We found that word " + element + " matches in array");
        });
    }, this);
    each()

</script>
ricristian
  • 466
  • 4
  • 17
0
$(function () {

    try {
        var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";

        var I = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"]

        for (var index = 0; index < I.length; index++) {
            if (nation.toString().toUpperCase().indexOf(I[index].toString().toUpperCase()) >= 0) {
                console.log(I[index].toString());
            }
        }
    }
    catch (err) {
        console.log(err);
    }
});

try this one.

Neeraj Pathak
  • 759
  • 4
  • 13