1

I need to count occurrences of an array in a string. I have problems with the special characters like ;/()

var msg = "hello world :)"; 
var tce = [":)", ":(", ":/" ];
var countOcurrences = 0;
for (var i = 0; i < tce.length; i++) {
  res = msg.match(/tce[i]/g);
  if (res != null) countOcurrences += res.length;
}

I think with regular expression, it may become more easy.

Ishan Dhingra
  • 2,442
  • 5
  • 31
  • 42
MrVila
  • 95
  • 9

4 Answers4

2

Forget about using regex and just use a simple indexOf to check for number of occurances. This function will help you:

function countMatches(str, find) {
    var count = 0;
    var index = str.indexOf(find);
    while (index != -1) {
        count++;
        index = str.indexOf(find, index + 1);
    }
    return count;
}

which you can use like this:

var msg = "hello world :)";
var tce = [":)", ":(", ":/"];
var countOcurrences = 0;
for (var i = 0; i < tce.length; i++) {
    countOcurrences += countMatches(msg, tce[i]);
}

Here is a working example

musefan
  • 47,875
  • 21
  • 135
  • 185
0

Change the array values to this:

var tce = [":\)", ":\(", ":/" ];

You need to escape ( and ) while using regex.

Aashray
  • 2,753
  • 16
  • 22
0

In fact, you don't need any loops at all. Just construct one big regexp with alternatives (|) and match the string against it:

var tce = [":)", ":(", ":/"];

// http://stackoverflow.com/a/3561711/989121
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}

var re = RegExp(tce.map(RegExp.escape).join('|'), "g");

var msg = "hello :/ world :):)";
var countOcurrences = (msg.match(re) || "").length; // 3
georg
  • 211,518
  • 52
  • 313
  • 390
-1

Don't use a regular expression for exact string matches.

You can use indexOf, use the 2nd parameter offset to find and count all occurrences.

var pos = msg.indexOf(str);
if (pos === -1) {
    // no match
}
var last_pos = pos;

pos = msg.indexOf(str, last_pos + 1);
if (pos !== -1) {
    counter += 1;
}

Do that in a loop, basically ^

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 1
    `last_pos` needs to be incremented before before used in the subsequent `indexOf` calls, otherwise it will endlessly match the same index – musefan Nov 06 '13 at 11:26