Javascript String indexOf() count number of occurrences

Introduction

:The following example sets count to the number of occurrences of the letter e in the string str:

const str = 'To be, or not to be, that is the question.'
let count = 0// www  .j  a  v a 2s .co m
let position = str.indexOf('e')

while (position !== -1) {
  count++
  position = str.indexOf('e', position + 1)
}

console.log(count)  // displays 4



PreviousNext

Related