-2

If you want to count the number of occurrences of one string inside another, which approach is better in terms of simplicity and/or performance? -

  • using indexOf in a for/while loop
  • using a regular expression

And if it is the latter, then what is the best way to do it?

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • 1
    @vitaly-t Implement [Knuth–Morris–Pratt algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) if performance is vital. – tchelidze Mar 16 '16 at 06:33
  • @user340764, that answers the question indeed, thank you. I probably should just delete it then? – vitaly-t Mar 16 '16 at 06:35
  • @vitaly-t if you need to delete string after finding their indexes, [this](http://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript) link might be useful. – Bunti Mar 16 '16 at 06:41
  • just wondering how using split() then counting the size of the resulting array would fare. – Tibrogargan Mar 16 '16 at 07:02

1 Answers1

1

Try the following regular expression:

var temp = "This is a string.";

var count = (temp.match(/is/g) || []).length;
alert(count);
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • It is good, but I wanted to know which way is better. That link provided earlier answers it fully: http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string – vitaly-t Mar 16 '16 at 06:37