Check out the number of Occurrences using JavaScript

Advertisement
Post Pic

In some scenarios we will have catch hold of number of occurrences while coding, like for example: In a sentence or paragraph I need to find out number of occurrences of a * (Star), how can we handle this using JavaScript, its simple and efficient.

Example: “DeveloperSnippets was helpful to *Developers, *Designers, *Beginners, and to *Everybody”

1
2
3
var str = "DeveloperSnippets was helpful to *Developers, *Designers, *Beginners, and to *Everybody";
var occurences = str.match(/\*/g);
document.write(occurences.length);

Output: 4

Explanation of the code:
The below line does everything, ‘/g’ here is for global, means it will check all occurrences of * in a given string globally.

1
var occurences = str.match(/\*/g);

Related Entries...

You Might Like:

Advertisement

Please let us know your feedback about the article through the comments section below, we want to hear from you about our website. And your comment / advice may help us to serve you better in upcoming articles.

Thank You!
Vivekanand [Founder of DeveloperSnippets]

5 Responses

10.29.08

Hi Vivek,

It is very use full for me it saved my time.. :)

Happy blogging

-Ravinder

10.29.08

Hi
thaxs a lot :)

10.29.08

Not working perferctly for the below string

var str = “9999,400,000.00″;
var occurences = str.match(/\,/g);
document.write(occurences.length);

Output is 3 where it should be 2

10.29.08

Hi Mohamed,

I have executed your code which you have mentioned for me the output is “2″… I am wondering how you got “3″ as an output.

I have copied and pasted your code, and checked it accordingly – it is giving me “2″ only….

Could you please check once again!

Thanks,
Vivek

10.29.08

Awesome dude.
Thanks alot.

Leave Your Response

* Name, Email, Comment are Required

Write For Us

Online Sponsors

Start Foreign Exchange Trading today with the Forex Affiliate Program and also you can have access Online Forex News to know what happens every single moment.


Forex Floor


Switch to our mobile site