12
6

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.

JavaScript 文字・文字列が大文字(小文字)かどうか判定する方法いろいろ

Last updated at Posted at 2019-01-06

タイトル通りJavaScriptで文字・文字列の大文字小文字を調べる方法を色々。

正規表現で

//正規表現で 文字列すべてが大文字かどうか
const isUpperCase = str => {
  return /^[A-Z]+$/g.test(sr)
}
console.log(isUpperCase('AA')) // true
console.log(isUpperCase('aa')) // false
console.log(isUpperCase('Aa')) // false
//string.matchを使った正規表現で文字列がすべてが大文字ならtrue
const isUpperCase = str => {
  const arr = str.match(/^[A-Z]+$/)
  return arr ? true : false
}
console.log(isUpperCase('ABC')) // true
console.log(isUpperCase('abc')) // false
console.log(isUpperCase('Abc')) // false

String.toUpperCaseして比較する

//String.toUpperCase/String.toLowerCase を使って
const isUpperCase = str => {
  return str === str.toUpperCase() ? true : false
}
console.log(isUpperCase('STR')) // true
console.log(isUpperCase('stR')) // false
console.log(isUpperCase('str')) // false

UTF-16 コードを使って判定

//AからZのcharCodeAtの値の範囲から
const isUpperCase = str => {
  const codeA = 'A'.charCodeAt()
  const codeZ = 'Z'.charCodeAt()
  const code = str.charCodeAt()
  return codeA <= code && code <= codeZ
}
console.log(isUpperCase('A')) // true
console.log(isUpperCase('B')) // true
console.log(isUpperCase('Z')) // true

console.log(isUpperCase('a')) // false
console.log(isUpperCase('b')) // false
console.log(isUpperCase('z')) // false


//上記を利用して配列のいずれかに大文字が含まれるか
console.log(['A', 'B', 'c'].some(isUpperCase)) //true

//配列のすべてが大文字かどうか
console.log(['A', 'B', 'c'].every(isUpperCase)) //false

大文字の文字列と照らし合わせて

//ABC...Zの文字列に合致するか
const strAtoZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const isUpperCase = arr => {
  for (let i = 0; i < strAtoZ.length; i++) {
    if (arr === strAtoZ[i]) {
      return true
    }
  }
  return false
}
console.log(isUpperCase('A')) // true
console.log(isUpperCase('a')) // false

//配列にして
const isUpperCase = str => {
  const arr = STR.split('')
  return arr.indexOf(str) >= 0 ? true : false
}
console.log(isUpperCase('A')) // true
console.log(isUpperCase('a')) // false
12
6
1

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
12
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?