Coffeescript-string-substr

提供:Dev Guides
移動先:案内検索

CoffeeScript文字列-substr()

説明

このメソッドは、文字列の必要な部分文字列を返すために使用されます。 部分文字列の開始値と文字列の長さを示す整数値を受け入れ、必要な部分文字列を返します。 開始値が負の場合、* substr()*メソッドはそれを文字列の末尾からの文字インデックスとして使用します。

構文

以下に、JavaScriptの* substr()*メソッドの構文を示します。 CoffeeScriptコードで同じメソッドを使用できます。

string.substr(start[, length])

次の例は、CoffeeScriptコードでJavaScriptの* substr()メソッドを使用する方法を示しています。 このコードを *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;
  • コマンドプロンプト*を開き、以下に示すように.coffeeファイルをコンパイルします。
c:\> coffee -c coffee string_substr.coffee

コンパイル時に、次の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);

次に、*コマンドプロンプト*を再度開き、以下に示すようにCoffeeScriptファイルを実行します。

c:\> coffee string_substr.coffee

CoffeeScriptファイルを実行すると、次の出力が生成されます。

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