Coffeescript-string-search

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

CoffeeScript文字列-search()

説明

このメソッドは、オブジェクト形式の正規表現を受け入れ、呼び出し文字列で指定された正規表現を検索します。 一致する場合、文字列内の正規表現のインデックスを返し、一致しない場合、値 -1 を返します。

構文

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

string.search(regexp)

次の例は、CoffeeScriptコードでJavaScriptの* search()メソッドを使用する方法を示しています。 このコードを *string_search.coffee という名前のファイルに保存します

regex =/apples/gi
string = "Apples are round, and apples are juicy."

if string.search(regex) == -1
  console.log "Does not contain Apples"
else
  console.log "Contains Apples"
  • コマンドプロンプト*を開き、以下に示すように.coffeeファイルをコンパイルします。
c:\> coffee -c coffee string_search.coffee

コンパイル時に、次のJavaScriptが提供されます。

//Generated by CoffeeScript 1.10.0
(function() {
  var regex, string;

  regex =/apples/gi;

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

  if (string.search(regex) === -1) {
    console.log("Does not contain Apples");
  } else {
    console.log("Contains Apples");
  }

}).call(this);

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

c:\> coffee string_search.coffee

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

Contains Apples