CoffeeScript String - substr ()

Descrição

Este método é usado para retornar uma substring necessária de uma string. Ele aceita um valor inteiro que indica o valor inicial da substring e o comprimento da string e retorna a substring necessária. Se o valor inicial for negativo, entãosubstr() método usa-o como um índice de caractere do final da string.

Sintaxe

A seguir está a sintaxe de substr()método de JavaScript. Podemos usar o mesmo método no código CoffeeScript.

string.substr(start[, length])

Exemplo

O exemplo a seguir demonstra o uso de substr()método de JavaScript no código CoffeeScript. Salve este código em um arquivo com o nomestring_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;

Abra o command prompt e compilar o arquivo .coffee conforme mostrado abaixo.

c:\> coffee -c coffee string_substr.coffee

Na compilação, ele fornece o seguinte 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);

Agora, abra o command prompt novamente e execute o arquivo CoffeeScript conforme mostrado abaixo.

c:\> coffee string_substr.coffee

Na execução, o arquivo CoffeeScript produz a seguinte saída.

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