Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the pattern exists in the text using includes method.
DSA Javascript
const text = 'hello world'; const pattern = 'world'; const found = text.[1](pattern); console.log(found);
Attempts:
3 left
💡 Hint
Common Mistakes
Using indexOf returns position, not boolean.
Using search returns index or -1, not boolean.
✗ Incorrect
The includes() method returns true if the pattern is found in the text, otherwise false.
2fill in blank
mediumComplete the code to find the first index of the pattern in the text.
DSA Javascript
const text = 'abracadabra'; const pattern = 'cad'; const index = text.[1](pattern); console.log(index);
Attempts:
3 left
💡 Hint
Common Mistakes
Using includes returns boolean, not index.
Using match returns array or null, not index.
✗ Incorrect
indexOf() returns the first index where the pattern starts or -1 if not found.
3fill in blank
hardFix the error in the code to correctly find all occurrences of the pattern using RegExp.
DSA Javascript
const text = 'banana bandana'; const pattern = /ana/g; const matches = text.[1](pattern); console.log(matches);
Attempts:
3 left
💡 Hint
Common Mistakes
Using search returns only first index.
Using matchAll returns an iterator, not array.
✗ Incorrect
match() with global flag returns an array of all matches.
4fill in blank
hardFill both blanks to extract all starting indices of the pattern in the text.
DSA Javascript
const text = 'testtesttest'; const pattern = /test/g; const indices = []; let match; while ((match = pattern.[1](text)) !== null) { indices.push(match.[2]); } console.log(indices);
Attempts:
3 left
💡 Hint
Common Mistakes
Using search does not return match object.
Using lastIndex is a property of RegExp, not match.
✗ Incorrect
exec() returns match object with index property showing start position.
5fill in blank
hardFill all three blanks to create a function that returns all indices of a substring in a string.
DSA Javascript
function findAllIndices(text, pattern) {
const indices = [];
let pos = 0;
while (true) {
const index = text.[1](pattern, pos);
if (index === [2]) break;
indices.push(index);
pos = index + [3];
}
return indices;
}
console.log(findAllIndices('abracadabra', 'abra'));Attempts:
3 left
💡 Hint
Common Mistakes
Using includes returns boolean, not index.
Not advancing pos causes infinite loop.
✗ Incorrect
indexOf finds substring from position pos; -1 means no more matches; advance pos by pattern length.
