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
Comparing ascii scores of strings - JavaScript
ASCII is a 7-bit character encoding standard where every character has a unique decimal code. In JavaScript, we can use the charCodeAt() method to get the ASCII value of any character.
This article demonstrates how to compare two strings by calculating their ASCII scores (the sum of ASCII values of all characters) and finding the difference between them.
Understanding ASCII Values
Each character has a specific ASCII decimal value:
console.log('A'.charCodeAt(0)); // 65
console.log('a'.charCodeAt(0)); // 97
console.log(' '.charCodeAt(0)); // 32 (space)
console.log('1'.charCodeAt(0)); // 49
65 97 32 49
Calculating ASCII Score of a String
To calculate the total ASCII score, we sum up the ASCII values of all characters:
const calculateScore = (str = '') => {
return str.split("").reduce((acc, val) => {
return acc + val.charCodeAt(0);
}, 0);
};
// Test with simple examples
console.log(calculateScore('ABC')); // 65 + 66 + 67 = 198
console.log(calculateScore('abc')); // 97 + 98 + 99 = 294
198 294
Complete Solution: Comparing ASCII Scores
Here's the complete function that compares two strings and returns the absolute difference between their ASCII scores:
const str1 = 'This is the first string.';
const str2 = 'This here is the second string.';
const calculateScore = (str = '') => {
return str.split("").reduce((acc, val) => {
return acc + val.charCodeAt(0);
}, 0);
};
const compareASCII = (str1, str2) => {
const firstScore = calculateScore(str1);
const secondScore = calculateScore(str2);
console.log(`First string score: ${firstScore}`);
console.log(`Second string score: ${secondScore}`);
return Math.abs(firstScore - secondScore);
};
console.log(`Difference: ${compareASCII(str1, str2)}`);
First string score: 2518 Second string score: 2982 Difference: 464
How It Works
The solution works in three steps:
-
Split the string:
str.split("")converts the string into an array of characters -
Get ASCII values:
charCodeAt(0)returns the ASCII decimal value of each character -
Sum and compare:
reduce()accumulates the total, thenMath.abs()finds the absolute difference
Alternative Approach Using for Loop
const calculateScoreLoop = (str) => {
let score = 0;
for (let i = 0; i < str.length; i++) {
score += str.charCodeAt(i);
}
return score;
};
console.log(calculateScoreLoop('Hello')); // Test
500
Conclusion
Comparing ASCII scores involves summing character codes using charCodeAt() and finding the absolute difference. This technique is useful for string similarity comparisons and text analysis algorithms.
