str.indexOf(substr) == 0
str.slice(0, 10) == substr
Which one of the above two is better? Is there any better way?
str.indexOf(substr) == 0
str.slice(0, 10) == substr
Which one of the above two is better? Is there any better way?
The performance of the first depends on the length of the string str
as it requires scanning the entire string. If str
is large it could take a long time to find whether or not the substring is contained within it.
If your input string could be large prefer the second.
Another option is:
str.lastIndexOf(substr, 0) == 0
This avoids scanning the entire string and avoids creating a temporary string.
If performance matters, I'd suggest measuring it for your specific data.
A (very) quick test suggests that the difference is probably negligible in Chrome, but that Firefox is substantially quicker with indexOf
(for short strings, at least).
Off the top of my head, I'd say to use:
str.indexOf(substr) == 0;
Simply because it doesn't need to create a new string from the first. Performance testing would be needed. Could vary by browser.