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...
Here is a simple and easily understandable snippet code, to remove duplicates from an existing array ...
In the following article we can have a look at the ways of creating new files in Ruby programming lan ...
This article will help beginners, that is who are new to jQuery and want to learn some tricks about j ...
Introduction: I would like to say this article going to help most of the developers who are in need ...
Do you want to know and detect visitor’s browser version using JavaScript, yeah here is the script th ...
Introduction: This article will helps you in removing any duplicate values from Multi Dimensional A ...
Hi Dev Folks, this topic explains you about different patterns used to match character combinations i ...
'How to select elements which are having multiple classes using jQuery', this question has raised whe ...
Introduction Recently, one of my reader came up with a query like "Why JavaScript is not running aft ...
Hi Guys, I would like to share a JavaScript snippet code which will remove special characters (like ! ...























5 Responses
Hi Vivek,
It is very use full for me it saved my time..
Happy blogging
-Ravinder
Hi
thaxs a lot
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
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
Awesome dude.
Thanks alot.