Skip to content
Advertisement

Search a string to find all the letters in JavaScript [closed]

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

const searchItem = () => {
  const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
  const searchDate = "i";
  for (let i = 0; i < source.length; i++) {
    let res = source.search(searchDate);
    if (res > 0) {
      document.getElementById("demo").innerHTML = res;
    } else if (res < 0) {
      document.getElementById("demo").innerHTML = "No results found";
    }
  }
}
<button onclick="searchItem()">Try it</button>

<p id="demo"></p>

Advertisement

Answer

You can use String#indexOf with the fromIndex argument to continuously search for the string.

const searchItem = () => {
  const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
  const searchDate = "i";
  const indexes = [];
  let i, prev = 0;
  while((i = source.indexOf(searchDate, prev)) !== -1){
    indexes.push(i);
    prev = i + searchDate.length;
  }
  if (indexes.length > 0) {
    document.getElementById("demo").innerHTML = indexes;
  } else {
    document.getElementById("demo").innerHTML = "No results found";
  }
}
<button onclick="searchItem()">Try it</button>

<p id="demo"></p>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement