Count string occurrence
http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string http://stackoverflow.com/questions/881085/count-the-number-of-occurences-of-a-character-in-a-string-in-javascript
Date tested:
25 days ago
User agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36
Test name
Executions per second
Use regex
21631072.0 Ops/sec
Use split
47845420.0 Ops/sec
Use indexOf
34807444.0 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
function regex(s, re) { var r = s.match(re); if (r) return r.length; return 0; } function split(s, oc) { return s.split(oc).length - 1; } function indexOf(s, oc) { var i = 0, count = 0; while ((i = s.indexOf(oc, i)) >= 0) { count++; i++; } return count; }
Tests:
Use regex
window.result = regex("This is a pen", /is/g);
Use split
window.result = split("This is a pen", "is");
Use indexOf
window.result = indexOf("This is a pen", "is");
Open this result on MeasureThat.net