Add up all the character code of a string in Javascript

Our Own Score

In this tutorial we will use the String.charCodeAt() method to returns a number indicating the Unicode value of the character at the given index of a string and then add them all up.

Step one is to create a string object with “Hello Wolrd!” as it’s content.

var hello = new String("Hello World!");

Next initiated the sum to zero.

var sum = 0;

Then we will loop through each character within that string and use the String.charCodeAt() method to returns a Unicode’s number and add it up with the sum variable.

for(var i = 0; i < hello.length; i++) {
	sum += hello.charCodeAt(i);
}

The sum of the total unicode values of that string is 1085.

String.charCodeAt() will always return a value that is less than 65,536.

0

Leave a Reply

avatar
  Subscribe  
Notify of