Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Calculating the weight of a string in JavaScript
In JavaScript, calculating the weight of a string means finding the sum of alphabetical positions of all characters. Each letter's weight is its position in the alphabet (a=1, b=2, c=3, etc.).
Understanding Character Weight
The weight of an English alphabet character is its 1-based index position:
- 'a' has weight 1
- 'b' has weight 2
- 'c' has weight 3
- 'z' has weight 26
Method 1: Using indexOf()
This approach uses a reference string to find each character's position:
const str = 'this is a string';
const calculateWeight = (str = '') => {
str = str.toLowerCase();
const legend = 'abcdefghijklmnopqrstuvwxyz';
let weight = 0;
for(let i = 0; i < str.length; i++){
const char = str[i];
const position = legend.indexOf(char);
if(position !== -1) { // Only count alphabetic characters
weight += (position + 1);
}
}
return weight;
};
console.log(calculateWeight(str));
172
Method 2: Using Character Codes
A more efficient approach using ASCII character codes:
const calculateWeightOptimized = (str = '') => {
str = str.toLowerCase();
let weight = 0;
for(let i = 0; i < str.length; i++){
const char = str[i];
if(char >= 'a' && char <= 'z') {
weight += (char.charCodeAt(0) - 96); // 'a' is 97, so subtract 96
}
}
return weight;
};
console.log(calculateWeightOptimized('hello'));
console.log(calculateWeightOptimized('abc'));
52 6
Step-by-Step Breakdown
Let's trace through the calculation for "abc":
const word = 'abc';
let total = 0;
for(let i = 0; i < word.length; i++) {
const char = word[i];
const weight = char.charCodeAt(0) - 96;
console.log(`'${char}' has weight: ${weight}`);
total += weight;
}
console.log(`Total weight: ${total}`);
'a' has weight: 1 'b' has weight: 2 'c' has weight: 3 Total weight: 6
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| indexOf() | O(n²) | High | Slower |
| Character Codes | O(n) | Medium | Faster |
Conclusion
String weight calculation sums alphabetical positions of characters. Use character codes for better performance, or indexOf() for clearer code readability.
Advertisements
