Creating string slices in every iteration is probably not efficient.
You don't need to iterate until str.length
, it would be enough until str.length - pattern.length
. This also helps with nonsense input where the pattern string is longer than the searched string.
The solution of @jfriend using indexOf
takes care of both of these issues.
Another important issue is the return value. It's not great to return two kinds of values: boolean or array. It's a strange design, and it makes the function harder to use. For example I cannot simply iterate over the results, I have to check for the value for first. I suggest to return an empty array when they're are no matches. The result will be much cleaner and easier to use. Note that an empty array is falsy in JavaScript, so you can still use it in a boolean context.
The word pattern may evoke a regular expression or something with wildcards. If recommend another name that suggests better a literal string. Perhaps "fragment".
.indexOf()
and slice only when you find a match. \$\endgroup\$