I search for the word “i” in the text, but it only shows the first “i” and does not show the rest of “i” I want you to show me the whole text though Help me please
JavaScript
x
12
12
1
const searchItem = () => {
2
const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
3
const searchDate = "i";
4
for (let i = 0; i < source.length; i++) {
5
let res = source.search(searchDate);
6
if (res > 0) {
7
document.getElementById("demo").innerHTML = res;
8
} else if (res < 0) {
9
document.getElementById("demo").innerHTML = "No results found";
10
}
11
}
12
}
JavaScript
1
3
1
<button onclick="searchItem()">Try it</button>
2
3
<p id="demo"></p>
Advertisement
Answer
You can use String#indexOf
with the fromIndex argument to continuously search for the string.
JavaScript
1
15
15
1
const searchItem = () => {
2
const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
3
const searchDate = "i";
4
const indexes = [];
5
let i, prev = 0;
6
while((i = source.indexOf(searchDate, prev)) !== -1){
7
indexes.push(i);
8
prev = i + searchDate.length;
9
}
10
if (indexes.length > 0) {
11
document.getElementById("demo").innerHTML = indexes;
12
} else {
13
document.getElementById("demo").innerHTML = "No results found";
14
}
15
}
JavaScript
1
3
1
<button onclick="searchItem()">Try it</button>
2
3
<p id="demo"></p>