In this article we’ll count the number of characters present in string using JavaScript. Master character counting in JavaScript! This guide explores efficient methods to count characters with and without spaces from a given string, empowering you to tackle various text processing tasks.
First we’ll count the characters' presence in the string including space. A simple way to count the length of the string.
JavaScript
let string = " Hello welcome to maketechstuff.com ";
let output = string.length;
console.log(string);
console.log(output);
Output:
If you want to count only the characters in a string, excluding spaces, you'll need to remove all spaces from the string before counting.
Here are three approaches to do that:
Approach 1:
- Divide the string into an array using the split() method, using spaces as delimiters.
- Combine all elements of the array into a single variable through for loop.
- Calculate the length of the resulting string using length property.
JavaScript
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let split = string.trim().split(" ");
for (let i = 0; i < split.length; i++) {
const element = split[i];
output += element;
}
console.log(string);
console.log(output);
console.log(output.length);
Output:
Approach 2:
Determine the length of the string after removing all spaces using the replace method and a regular expression.
JavaScript
let string = " Hello welcome to maketechstuff.com ";
let output = string.replace(/\s+/g, "");
console.log(string);
console.log(output);
console.log(output.length);
Output:
Approach 3:
First, we'll split the string from space, making into an array using the split method.
Next, we'll create a new array using the filter method. This method excludes empty elements, effectively removing all empty elements from the array and create a new array.
To determine the number of characters, we can join the array elements back into a string using the join method and then count the length of the resulting string.
JavaScript
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let array = string.trim().split(" ");
let new_array = array.filter(function (array) { return array })
output = new_array.join("");
console.log(string);
console.log(output);
console.log(output.length);
So that's how you can count the characters from the given string using JavaScript. If you have any questions or suggestions you can write in the comment section.
You may like:
- How to create character counter with and without including space using JavaScript.
- How to count the number of words present in a string using JavaScript.
- How to create a live word counter using JavaScript.
- Detect and count the number of spaces in string using JavaScript.
Share your thoughts.