2017-01-02 11 views
-1

入力ボックスがあり、入力したテキストに応じて特定のアラートが必要です。「hello」以外の文字を入力すると、「TypeError:input.match(...)is null」というエラーが表示され続けます。「TypeError:input.match(...)is null」というメッセージが表示されるのはなぜですか?

マイコード:String.prototype.match()用のMozilla Developer Networkのドキュメントから

<html> 
<body> 
<form name="form5"> 
    <input type=text size=51 name="input"> 
    <input onClick=auswert() type=button value="submit"> 
</form> 
<script type="text/javascript"> 

function auswert() { 
var input = document.form5.input.value; 

if (input.match(/hello/g).length == 1) alert("hello"); 
else alert("bye"); 
} 

</script> 
</body> 
</html> 
+1

一致するものがない場合は、 'input.match(/ハロー/ g)は、'、 'null'なのでを返すため。 [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)を読むことは常に有用です。 – Teemu

+0

を読んだり、ドキュメントを読んでいない場合は、より良いロジックを作成してください。 'if((input.match(/ hello/g))&&(input.match(/ hello/g).length == 1))' –

答えて

0

「マッチ全体の結果を含む配列および任意の括弧は、キャプチャし、結果を一致、ヌル何の一致がない場合。」

input.match(/hello/g)がnullを返す。次に、nulllengthを呼び出しています。 nullには、呼び出すことのできる機能がありません。

私はあなたが試すことをお勧めしたい:

if (input.match(/hello/g) == null) { 
    // No Matches 
    alert("bye"); 
} else { 
    // Matches 
    alert("hello"); 
} 
関連する問題