Skip to content Skip to sidebar Skip to footer

Count Occurances In String From Keyword Array In Javascript

I have an array: var locations = ['Afghanistan','Albania','Algeria','New York']; and a string: var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New Yo

Solution 1:

Here is my version:

functioncountItems(a, s) {
    var x, i, output = {};
    for (x = 0; x < a.length; x++) {
        i = 0;
        output[a[x]] = 0;
        while ((i = s.indexOf(a[x], i)) > -1) {
            output[a[x]]++;
            i++
        }
    }
    returnoutput;
}

var result = countItems(locations, string);
// result['Albania'] === 0

Try it out here.

Solution 2:

Try something like this. You could modify what you do with count -- store it in another array, display it (which is what this script does), etc.

var locations = ['Afghanistan','Albania','Algeria','New York'];
var str = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';


for(var i=0; i<locations.length; i++) {
    var pattern = newRegExp(locations[i], "g");
    var m = str.match(pattern);
    if (m != null)
    {
       var count = m.length; // the countalert("There are " + count + " occurrences of " + locations[i]);
    }
}

Solution 3:

<scriptlanguage="JavaScript">var locations = ['Afghanistan','Albania','Algeria','New York'];

var string1 = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';

for (var i=0;i<locations.length;i++) {
  nCount = string1.split(locations[i]).length-1;
  document.write(locations[i] + ' is found ' + nCount + ' times<br>');
}

</script>

Solution 4:

This code only instantiates oneRegExp object and uses a reverse while-loop. I'm pretty sure this is as fast as you can go without breaking the laws of physics :)

This is whats happening:

  1. Construct regular expression string using a reverse while-loop
  2. New up just one RegExp object, and match() it on the string
  3. Count the length of the array returned by the match() function

Here's the implementation:

var countries = ["Afganistan", "America", "Island"];
var sentence = "I love Afganistan, America.. And I love America some more";

functioncountOccurrences(a, s)
{
    var re = "",
        l = a.length,
        m;

    while (l)
    {
        l--;

        re += a[l];

        if (l > 0) re += "|";
    }

    m = s.match(newRegExp(re, "gi")) || [];

    return m.length;
}

Note: I am of course expecting the entries in the array to be sanitized for any special characters that will break the regular expression constructed within the function.

var occurrences = functioncountOccurrences(countries, sentence); // returns 3

Post a Comment for "Count Occurances In String From Keyword Array In Javascript"