const str = "JavaScript is awesome. JavaScript is popular.";
const sub = "JavaScript";
let index = str.indexOf(sub);
while (index !== -1) {
console.log(index);
index = str.indexOf(sub, index + 1);
}
Output:
0
23
Explanation:
1. The `indexOf` method is used to find the first occurrence of the substring "JavaScript" in the string `str`.
It returns the index of the first occurrence, which is 0.
2. The `while` loop continues to search for the substring "JavaScript" starting from the index after the last
found occurrence (index + 1). The next occurrence is found at index 23.
3. The loop continues until `indexOf` returns -1, indicating that there are no more occurrences of the
substring in the string. The final output is the indices of the occurrences of "JavaScript" in the string,
which are 0 and 23.
No comments:
Post a Comment