Search a string to find all the letters in JavaScript

Viewed 79

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>

6 Answers

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>

.search() returns the index of the first match. It does not search the whole string.


Since the for loop in the code isn't used, You're probably trying use that loop to compare each char in the string;

const searchItem = () => {
    const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
    const searchDate = "i";
    let res = 0;

    // For each character in source
    for (let i = 0; i < source.length; i++) {
        
        // If current char matches searchDate
        if (source[i] === searchDate) {
        
            // Bumb result counter
            res++;
        }
    }

    // After looping through all the chars, show result based on res
    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>

const searchItem = () => {
  const str = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
  const res = str.split("i").length - 1;
  if (res > 0) {
    document.getElementById("demo").textContent = res;
  } else {
    document.getElementById("demo").textContent = "Invalid";
  }
}
<button onclick="searchItem()">Try it</button>

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

If your aim is to only find the occurrences of letters in word then that can be done by simple split method.

const str = "Lorem ipsum dolor sit amet consectetur adipisicing elit.";
const result = str.split("i").length - 1;
console.log(result);

Seems to me like you're trying to count the occurrences within a string, this should do:

var findOccurrences = () => {
   var searchQuery = document.getElementById('searchQuery').value;
   var source = document.getElementById('source').value;

   var regExp = new RegExp(searchQuery, 'g');
    
   var match = source.match(regExp);
   var occurrences = 0;
   
   if(match) {
    occurrences = match.length;
   }

   document.getElementById('demo').innerHTML = occurrences > 0 ? occurrences : "No results found";
 }
<input id="source" value="Lorem ipsum dolor sit amet consectetur adipisicing elit."/>
<input id="searchQuery" />
<button onclick="findOccurrences()">Try it</button>
<div id="demo"></div>

another way. get the length of the string. replace all occurrences and get the length again, the difference is your result.

const searchItem = () => {
      const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
      const searchDate = "i";
      const initialLen = source.length;
      const replacedLen = source.split(searchDate).join("").length;
      const diff = initialLen - replacedLen;
      if(diff > 0){
        document.getElementById("demo").innerHTML = diff
      }
      else{
        document.getElementById("demo").innerHTML = "No results found";
      }
}
<button onclick="searchItem()">Try it</button>

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

<script>
    const searchItem = () => {
        const source = "Lorem ipsum dolor sit amet consectetur adipisicing elit."
        const searchDate = "i";
        const demo = document.getElementById("demo");
        for (let i = 0; i < source.length; i++)
            if (source[i] === searchDate)
                demo.innerHTML += i + ' ';
        if (demo.innerHTML === '')
            demo.innerHTML = "No results found";
    }
</script>
Related