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.

2
  • Do you mean you want to count how many times any item from your array appears in the string? Commented Nov 6, 2013 at 10:51
  • If the space before :) is mandatory means split(" ") will help you Commented Nov 6, 2013 at 10:54

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Is nice code but I think it dont work with 0 ocurrences. ^^ ty for answer
0

Change the array values to this:

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

You need to escape ( and ) while using regex.

Comments

-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 ^

1 Comment

last_pos needs to be incremented before before used in the subsequent indexOf calls, otherwise it will endlessly match the same index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.