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 

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 = 'a' && char 

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 

'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.

Updated on: 2026-03-15T23:19:00+05:30

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements