Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Count string occurrence
(version: 0)
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
Comparing performance of:
Use regex vs Use split vs Use indexOf
Created:
9 years ago
by:
Registered User
Jump to the latest result
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");
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (3)
Previous results
Fork
Test case name
Result
Use regex
Use split
Use indexOf
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
4 months ago
)
User agent:
Mozilla/5.0 (X11; Linux x86_64; rv:146.0) Gecko/20100101 Firefox/146.0
Browser/OS:
Firefox 146 on Linux
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
Use regex
2597234.8 Ops/sec
Use split
2611738.5 Ops/sec
Use indexOf
2937491.8 Ops/sec
Related benchmarks:
Split strings by character count
Split strings by character count (regex vs. slice vs. substr)
count number of chars in a string
Count char occurrence in string
Comments
Confirm delete:
Do you really want to delete benchmark?