CoffeeScript String - charAt()



Description

The charAt() method of JavaScript returns the character of the current string that exists in the specified index.

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is one less than the length of the string. (stringName_length - 1 )

Syntax

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

string.charAt(index);

It accepts an integer value representing the index of the String and returns the character at the specified index.

Example

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

str = "This is string"  

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

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

c:\> coffee -c string_charat.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 character at the index (0) is:" + str.charAt(0));

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

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

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

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

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

}).call(this); 

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

c:\> coffee string_charat.coffee

On executing, the CoffeeScript file produces the following output.

The character at the index (0) is:T
The character at the index (1) is:h
The character at the index (2) is:i
The character at the index (3) is:s
The character at the index (4) is:
The character at the index (5) is:i
coffeescript_strings.htm
Advertisements