Overview
Implement textSearch(text, pattern) that returns an array of starting indices where pattern appears in text.
Examples
textSearch('ababab', 'ab'); // [0, 2, 4]
textSearch('hello', 'xyz'); // []Solution
Reveal solution
function textSearch(text, pattern) {
if (!pattern) return [];
const indices = [];
let idx = text.indexOf(pattern);
while (idx !== -1) {
indices.push(idx);
idx = text.indexOf(pattern, idx + 1);
}
return indices;
}text-search.js
Text Search
mediumcodingJavaScriptStrings
Overview
Implement textSearch(text, pattern) that returns an array of starting indices where pattern appears in text.
Examples
textSearch('ababab', 'ab'); // [0, 2, 4]
textSearch('hello', 'xyz'); // []Solution
Reveal solution
function textSearch(text, pattern) {
if (!pattern) return [];
const indices = [];
let idx = text.indexOf(pattern);
while (idx !== -1) {
indices.push(idx);
idx = text.indexOf(pattern, idx + 1);
}
return indices;
}NameTopicDifficulty
103 of 103 problems