Member-only story
12 useful JavaScript Code Snippet
In this post we will look 12 useful javascript code snippet
JavaScript is one of the most popular programming languages around. It has become a staple for dynamic and interactive web pages. But whether you’re a beginner or a seasoned developer, it never hurts to have a few code snippets up your sleeve. So in this post, I’m going to share 12 useful JavaScript code snippets with explanations.
Reverse a string
Let’s start with a simple one. This code snippet reverses the order of characters in a string.
function reverseString(str) {
return str.split("").reverse().join("");
}
The reverseString()
function takes a string as input and returns the same string with the characters in reverse order. It uses the split()
method to convert the string into an array of characters, then the reverse()
method to reverse the order of the array, and finally the join()
method to convert the array back into a string.
Count occurrences of a character
This code snippet counts the number of occurrences of a character in a string.
function countOccurences(str, char) {
return str.split(char).length - 1;
}
countOccurences("test", "t"); // 2