如何在字符串中找到至少1个大写字母?

时间:2017-12-12 06:23:45

标签: javascript ecmascript-6

在es6 js中我有:



good = word => {
  word.split('').includes(w => w === w.toUpperCase())
}

console.log(good('Bla'))




如何在字符串中找到1个大写字母时返回true?

4 个答案:

答案 0 :(得分:4)

您可以使用带有test全部大写字母[A-Z]的正则表达式character set字符串:



const good = word => /[A-Z]/.test(word);

console.log(good('Bla'));
console.log(good('bla'));




答案 1 :(得分:3)

虽然有更简单的方法可以做到这一点(Tushar评论中的正则表达式就是其中之一),但可以通过以下方式修复您的尝试:

  • 删除大括号,以便该函数实际返回一个值。
  • 使用.some(),它以函数作为参数。 .includes()没有。
  • 添加const,以便您实际宣布自己的功能。

const good = word => word.split('').some(w => w === w.toUpperCase())

console.log(good('Bla'))
console.log(good('bla'))

答案 2 :(得分:-1)

如果你想要它的索引,你也可以这样做。

function findUpperCase(str) {
    return str.search(/[A-Z]/);
}

答案 3 :(得分:-1)

// The string which will go thorough the test
let theString = 'Hello World'

// Function to find out the answer
function stringCheck (receivedString) {
  // Removing special character, number, spaces from the string to perform exact output
  let stringToTest = receivedString.replace(/[^A-Z]+/ig, "")
  // Variable to count: how many uppercase characters are there in that string 
  let j = 0
  // Loop thorough each character of the string to find out if there is any uppercase available
  for (i = 0; i < stringToTest.length; i++) {
    // Uppercase character check
    if (stringToTest.charAt(i) === stringToTest.charAt(i).toUpperCase()) {
      console.log('Uppercase found: ' + stringToTest.charAt(i))
      j++
    }
  }
  console.log('Number of uppercase character: ' + j)
  // Returning the output
  if (j >= 1) {
    return true
  } else {
    return false
  }
}

// Calling the function
let response = stringCheck(theString)
console.log('The response: ' + response)