CoffeeScript String - substr()



Description

This method is used to return a required substring of a string. It accepts an integer value indicating the starting value of the substring and the length of the string and returns the required substring. If the start value is negative, then substr() method uses it as a character index from the end of the string.

Syntax

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

string.substr(start[, length])

Example

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

str = "Apples are round, and apples are juicy.";
         
console.log "The sub string having start and length as (1,2) is : " + str.substr 1,2
console.log "The sub string having start and length as (-2,2) is : " + str.substr -2,2
console.log "The sub string having start and length as (1) is : " + str.substr 1
console.log "The sub string having start and length as (-20, 2) is : " + str.substr -20,2
console.log "The sub string having start and length as (20, 2) is : " + str.substr 20,2;

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

c:\> coffee -c coffee string_substr.coffee

On compiling, it gives you the following JavaScript.

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

  str = "Apples are round, and apples are juicy.";

  console.log("The sub string having start and length as (1,2) is : " + str.substr(1, 2));

  console.log("The sub string having start and length as (-2,2) is : " + str.substr(-2, 2));

  console.log("The sub string having start and length as (1) is : " + str.substr(1));

  console.log("The sub string having start and length as (-20, 2) is : " + str.substr(-20, 2));

  console.log("The sub string having start and length as (20, 2) is : " + str.substr(20, 2));

}).call(this);

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

c:\> coffee string_substr.coffee 

On executing, the CoffeeScript file produces the following output.

The sub string having start and length as (1,2) is : pp
The sub string having start and length as (-2,2) is : y.
The sub string having start and length as (1) is : pples are round, and apples are juicy.
The sub string having start and length as (-20, 2) is : nd
The sub string having start and length as (20, 2) is : d
coffeescript_strings.htm
Advertisements