0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JSで文字列が数字か判断する

Last updated at Posted at 2023-05-15
let string = "aaa";
let number = "123";
let stringContainingNumber = "aaa123";

//A
let checkIfNumber = /^[0-9]+$/; //正規表現、終始半角数字で1文字以上の文字列を示す

checkIfNumber.test(string); //false 
checkIfNumber.test(number);//true
checkIfNumber.test(stringContainingNumber);//false

//B
let checkIfNaN = /[^0-9]/; //正規表現、半角数字以外のある1文字を示す

checkIfNaN.test(string); //true 
checkIfNaN.test(number);//false
checkIfNaN.test(stringContainingNumber);//true

正規表現.test(文字列)は
正規表現と文字列の間に一致するものがあった場合は、true、そうでない場合は、false。
Aは最初から最後まで数字、という正規表現に一致したらtrue、Bは数字以外の何らかの文字がひとつでも入っていたらtrue、なので両方同じ。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?