-1

指定された文字列 foo が指定された文字列 bar で終わる場合に true を返す正規表現を作成しようとしています。例えば:

function solution(str, ending)
{
  var pattern = "/" + ending + "$/";
  var regex = new RegExp(pattern, "i");
  console.log( str + ", " + ending + " , " + regex.source);
  return regex.test(str);
}

ただし、次の入力を使用してこれをテストすると:

console.log( solution("samurai", "ai") );

次のコンソール出力が得られます。

samurai, ai , /ai$/
false 

パターンは正しいように思えますが、なぜ「samurai」が「ai」で終わるのに false を返すのでしょうか?

4

2 に答える 2

2

コンストラクターを呼び出す場合、パターンを文字で囲むRegExp必要はありません。/これは、正規表現リテラルを使用している場合のみです。

これを試して:

function solution(str, ending)
{
  var pattern = ending + "$";
  var regex = new RegExp(pattern, "i");
  console.log( str + ", " + ending + " , " + regex.source);
  return regex.test(str);
}
于 2013-10-11T02:29:25.273 に答える