In this blog post, we count the number of characters in string In javascript. Such if we a string like: “Hello, codemen. How are you?” In this string, we want to count the number of characters “y”. the result should be 1.
Method 1 : Using Match
The match()
method retrieves the result of matching a string against a regular expression.
Script
<script>
var str = "Hello, codemen. How are you?";
console.log((str.match(/y/g) || []).length);
</script>
Result:
1
Method 2: Using Split
The split()
method divides a String
into an ordered list of substrings, puts these substrings into an array, and returns the array. After that we find the lenght of array and minus 1.
<script>
var str = "Hello, codemen. How are you?";
console.log((str.split("o").length - 1));
</script>
Result:
4

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.