0

I was given a text. How can I search for a particular string in that and how many times it appears using JavaScript?

Text:

This is a boy . This boy is very smart . This boy does miracles.

So if I want search for string = "boy " .

How can I do that using JavaScript?

What I did ? I tried using search function of JavaScript. Is that right to use?

Thank you so much in advance!!!

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf – mplungjan May 02 '17 at 08:15
  • 1
    https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions – mplungjan May 02 '17 at 08:16
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split and https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter or map – mplungjan May 02 '17 at 08:17
  • @mplungjan: This question seems not to be a duplicate of the referenced earlier question as in this question the user is also asking for the _number of occurrences_. To achieve this I suggest to use a recursive function: split the string after the first occurrence of **boy** and the search for **boy** in the remainder of the string again. And count how many times the function has to be called. Or you split the string using **boy** as separator - but take care if **boy** is at the start or the end of the string. And count the number of elements in the resulting array. – ikellenberger May 02 '17 at 08:37
  • http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string – mplungjan May 02 '17 at 09:38

0 Answers0