2017-02-01 4 views
-3

これは本当に困惑しています。.matchと.substrが一緒に動作しないjavascriptの問題

これは私にとってうまくいきます。

var result = "this is my abc book"; 
 
console.log(result); // displays "this is my abc book" 
 
var res = result.substr(3); 
 
console.log(res); // displays "s is my abc book"

しかし、私はフィールドに "これは私のABCの本である" 置くと仮定し、このコードを実行し、問題がある:

var str = "this is my abc book"; //$(this).val(); 
 
console.log(str); // displays "this is my abc book" 
 
var result = str.match(/abc.*/i); 
 
console.log(result); // displays "abc book" 
 
var res = result.substr(3); 
 
console.log(res); // does not display at all!

は、

.Matchは.substrで切り取れないものを返しているようです。

私はまた、.splitと.substringを試しましたが、喜びはしませんでした。

つまり、正規表現の一致からsubstrを取得するにはどうすればよいですか?

+9

[*マッチ*](http://ecma-international.org/ecma-262/7.0/index.html#sec-string.prototype.match)アレイを返しますか* null *、文字列ではありません。 – RobG

+0

正常に動作しない場合は、コンソールを確認してください。コードが破損する可能性があります – Rajesh

+0

substrはあなたにもあなたを混乱させるので、substrの代わりに部分文字列を使用してください – mplungjan

答えて

1

.match()は配列を返し、それゆえあなたはresultすなわちresult[0]代わりのresult)内のデータにアクセスするためにインデックスを使用する必要があります。

以下のスニペットを確認してください。

var str = "this is my abc book"; //$(this).val(); 
 
console.log(str); // displays "this is my abc book" 
 
var result = str.match(/abc.*/i); 
 
console.log(result); // displays "abc book" 
 
var res = result[0].substr(3); 
 
console.log(res); // does not display at all!

+1

コメントが十分であり、RobGのコメントは – Rajesh

+1

です。コメントは回答ではありません(ここではstackexchangeではありません)。 – elboletaire

+0

したがって、質問には、回答ではなく重複として削除またはマークするようにフラグを付けることができます。 – mplungjan

関連する問題