CoffeeScript String - charCodeAt()



Description

This method returns a number indicating the Unicode value of the character at the given index.

Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match of the ASCII character encoding. charCodeAt() always returns a value that is less than 65,536.

Syntax

Given below is the syntax of charCodeAt() method of JavaScript. We can use the same method from the CoffeeScript code.

string. charCodeAt(index)

It accepts an integer value representing the index of the String and returns the Unicode value of the character existing at the specified index of the String. It returns NaN if the given index is not between 0 and 1 less than the length of the string.

Example

The following example demonstrates the usage of charCodeAt() method of JavaScript in CoffeeScript code. Save this code in a file with name string_charcodeat.coffee

str = "This is string"

console.log "The Unicode of the character at the index (0) is:" + str.charCodeAt 0 
console.log "The Unicode of the character at the index (1) is:" + str.charCodeAt 1 
console.log "The Unicode of the character at the index (2) is:" + str.charCodeAt 2 
console.log "The Unicode of the character at the index (3) is:" + str.charCodeAt 3 
console.log "The Unicode of the character at the index (4) is:" + str.charCodeAt 4 
console.log "The Unicode of the character at the index (5) is:" + str.charCodeAt 5

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c string_charcodeat.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var str;

  str = "This is string";

  console.log("The Unicode of the character at the index (0) is:" + str.charCodeAt(0));

  console.log("The Unicode of the character at the index (1) is:" + str.charCodeAt(1));

  console.log("The Unicode of the character at the index (2) is:" + str.charCodeAt(2));

  console.log("The Unicode of the character at the index (3) is:" + str.charCodeAt(3));

  console.log("The Unicode of the character at the index (4) is:" + str.charCodeAt(4));

  console.log("The Unicode of the character at the index (5) is:" + str.charCodeAt(5));

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee string_charcodeat.coffee

On executing, the CoffeeScript file produces the following output.

The Unicode of the character at the index (0) is:84
The Unicode of the character at the index (1) is:104
The Unicode of the character at the index (2) is:105
The Unicode of the character at the index (3) is:115
The Unicode of the character at the index (4) is:32
The Unicode of the character at the index (5) is:105
coffeescript_strings.htm
Advertisements