检查单词的第一个字母是否为大写字母

发布于 2024-12-19 01:58:44 字数 42 浏览 2 评论 0原文

JavaScript 是否可以判断一个单词的第一个字母是否为大写字母?

Is it possible in JavaScript to find out if the first letter of a word is a capital letter?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

秋叶绚丽 2024-12-26 01:58:44

更新

用我认为当今最有效的方法进行更新。

您可以使用 Unicode 属性转义正则表达式如果支持适合您。在这种情况下,您可以使用大写字母 Lu常规类别属性 >。

function isUppercase(word){
  return /^\p{Lu}/u.test( word );
}

旧答案

var word = "Someword";
console.log( word[0] === word[0].toUpperCase() );

var word = "Someword";
console.log( /[A-Z]/.test( word[0]) );

var word = "Someword";
console.log( /^[A-Z]/.test( word) );

请参阅 toUpperCase()测试()

update

Updating with what i think is the most valid approach nowadays.

You can use a Unicode property escapes Regular expression if the support suits you. In this case you can use the General category property for Uppercase Letter Lu.

function isUppercase(word){
  return /^\p{Lu}/u.test( word );
}

older answers

var word = "Someword";
console.log( word[0] === word[0].toUpperCase() );

or

var word = "Someword";
console.log( /[A-Z]/.test( word[0]) );

or

var word = "Someword";
console.log( /^[A-Z]/.test( word) );

See toUpperCase() and test()

情丝乱 2024-12-26 01:58:44

本页上的其他答案适用于已知仅包含非重音 AZ 字母的字符串。如果您不能保证这一点(例如用户输入),它们可能会给出意想不到的结果:对于不可大写的首字母(例如“1940s”或“中文”)的误报,或者对于重音或非罗马大写首字母(例如“Łukasz”或“)的误报” Александра”。

如果首字母是任何大写字母,则此变体返回 true;如果它是大写字母:

function initialIsCapital( word ){
  return word[0] !== word[0].toLowerCase();
}

使用 .charAt(0) 而不是 < code>[0] 如果您需要 IE8 支持。哪个更快因浏览器而异

这避免了其他答案的两个潜在陷阱:

  • 使用[AZ]的正则表达式将无法匹配重音字母和其他类似的非AZ大写字母,例如Åland(斯堪的纳维亚群岛)和Łukasz(常见波兰语名称),包括非拉丁字母的大写字母,例如西里尔语或希腊语(例如Александра)。

  • 使用 word[0] === word[0].toUpperCase() 的方法将对以非字母开头的单词返回 true,例如 1940s17th123reg(公司名称)、缩写如 2mrw 或某些非洲语言中的单词,例如!xūúnǂǐ-sì。它还会将任何来自字母表中不包含大写字母的输入视为大写字母(例如中文)。

由于这种任意输入安全的方法与其他方法一样简单且可读性不亚于其他方法,因此即使您没有预料到此类异常,也可能更好地使用它。

这是一个快速测试:

function a(word){
  return word[0] !== word[0].toLowerCase();
}
function b(word){
  return word[0] === word[0].toUpperCase();
}
function c(word){
  return /^[A-Z]/.test( word );
}
function test(word, answer){
  console.log( 'Should be '+answer+':',  a(word), b(word), c(word), '-------', word );
}

test( 'Łukasz', true ); // regex test fails, returns false
test( 'Александра', true ); // regex test fails, returns false
test( '1940s', false ); // .toUpperCase() test fails, returns true
test( '中文', false ); // .toUpperCase() test fails, returns true

test( 'ß', false ); // All pass on German "sharp S" that has no uppercase
test( 'Z̢̜̘͇̹̭a͎͚͔͕̩̬̭͈͞l̩̱̼̤̣g̲̪̱̼̘̜͟ợ̮̱͎̗̕ͅͅ', true ); // All pass. Phew, Zalgo not awakened 

The other answers on this page are fine for strings that are known to only contain non-accented A-Z letters. If you can't guarantee this (e.g. user input), they may give unexpected results: false positives for uncapitalisable initials like "1940s" or "中文", or false negatives for accented or non-Roman capital initials like "Łukasz" or "Александра".

This variant returns true if the initial is any capital letter, and only if it's a capital letter:

function initialIsCapital( word ){
  return word[0] !== word[0].toLowerCase();
}

Use .charAt(0) instead of [0] if you need IE8 support. Which is faster varies between browsers.

This avoids two potential pitfalls with the other answers:

  • Regexes using [A-Z] will fail to match accented and other similar non-A-Z capitalised letters such as in Åland (Scandinavian islands) and Łukasz (common Polish name), including capital letters in non-latin scripts such as Cyrillic or Greek (e.g. Александра).

  • The approach using word[0] === word[0].toUpperCase(), will return true on words that start with non-letters, such as 1940s, 17th, 123reg (company name), abbreviations like 2mrw, or some words in some African languages, such as !xūún or ǂǐ-sì. It'll also treat any input from an alphabet that doesn't have capital letters as being capital letters (e.g. 中文).

Since this arbitrary-input-safe approach is just as simple and no less readable than the alternatives, it's probably better to use this even if you don't anticipate such exceptions.

Here's a quick test:

function a(word){
  return word[0] !== word[0].toLowerCase();
}
function b(word){
  return word[0] === word[0].toUpperCase();
}
function c(word){
  return /^[A-Z]/.test( word );
}
function test(word, answer){
  console.log( 'Should be '+answer+':',  a(word), b(word), c(word), '-------', word );
}

test( 'Łukasz', true ); // regex test fails, returns false
test( 'Александра', true ); // regex test fails, returns false
test( '1940s', false ); // .toUpperCase() test fails, returns true
test( '中文', false ); // .toUpperCase() test fails, returns true

test( 'ß', false ); // All pass on German "sharp S" that has no uppercase
test( 'Z̢̜̘͇̹̭a͎͚͔͕̩̬̭͈͞l̩̱̼̤̣g̲̪̱̼̘̜͟ợ̮̱͎̗̕ͅͅ', true ); // All pass. Phew, Zalgo not awakened 

独自唱情﹋歌 2024-12-26 01:58:44

仅适用于英文字母:

'A' => 65
'Z' => 90

意思是,[65, 90]之间的每个数字都是大写字母:

function startsWithCapitalLetter(word) {
  return word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90;
}

For English letters only:

'A' => 65
'Z' => 90

Meaning, every number between [65, 90] is a capital letter:

function startsWithCapitalLetter(word) {
  return word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90;
}
时光清浅 2024-12-26 01:58:44

是的。

var str = "Hello";
if(str[0].toUpperCase() == str[0])
{
   window.alert('First character is upper case.');  
}

Yes.

var str = "Hello";
if(str[0].toUpperCase() == str[0])
{
   window.alert('First character is upper case.');  
}
浴红衣 2024-12-26 01:58:44

您可以通过多种方式完成此操作:

var myWord = "Hello";

// with string functions
if (myWord.charAt(0) === myWord.charAt(0).toUpperCase()) { /* is upper */ }

// or for newer browsers that support array-style access to string characters
if (myWord[0] === myWord[0].toUpperCase()) { /* is upper */ }

// with regex - may not be appropriate for non-English uppercase
if (/^[A-Z]/.test(myWord) { /* is upper */ }

请注意,对 myWord[0] 等字符的数组样式访问是 ECMAScript 5 功能,较旧的浏览器不支持,因此(目前)我可能会推荐使用 .charAt() 方法。

如果您需要经常进行此测试,您可以制作一个小功能:

function firstLetterIsUpper(str) {
   var f = str.charAt(0);   // or str[0] if not supporting older browsers
   return f.toUpperCase() === f;
}

if (firstLetterIsUpper(myWord)) { /* do something */ }

You can do it in several ways:

var myWord = "Hello";

// with string functions
if (myWord.charAt(0) === myWord.charAt(0).toUpperCase()) { /* is upper */ }

// or for newer browsers that support array-style access to string characters
if (myWord[0] === myWord[0].toUpperCase()) { /* is upper */ }

// with regex - may not be appropriate for non-English uppercase
if (/^[A-Z]/.test(myWord) { /* is upper */ }

Note that the array-style access to characters like myWord[0] is an ECMAScript 5 feature and not supported in older browsers, so (for now) I'd probably recommend the .charAt() method.

If you need to do this test a lot you could make a little function:

function firstLetterIsUpper(str) {
   var f = str.charAt(0);   // or str[0] if not supporting older browsers
   return f.toUpperCase() === f;
}

if (firstLetterIsUpper(myWord)) { /* do something */ }
木格 2024-12-26 01:58:44

使用字符串对象原型的 match 方法:

const word = 'Someword';
console.log(word.match(new RegExp(/^[A-Z]/)) !== null);

Using the match method of the string object prototype:

const word = 'Someword';
console.log(word.match(new RegExp(/^[A-Z]/)) !== null);

趴在窗边数星星i 2024-12-26 01:58:44
var string1 = "this is a string";
var string2 = "This is a string";

if(string1[0] == string1[0].toUpperCase())
    alert('is upper case');
else
    alert('is not upper case');


if(string2[0] == string2[0].toUpperCase())
    alert('is upper case');
else
    alert('is not upper case');
var string1 = "this is a string";
var string2 = "This is a string";

if(string1[0] == string1[0].toUpperCase())
    alert('is upper case');
else
    alert('is not upper case');


if(string2[0] == string2[0].toUpperCase())
    alert('is upper case');
else
    alert('is not upper case');
幼儿园老大 2024-12-26 01:58:44

Typescript

//userEntry input as string
//return boolean
oneUppercaseRequired(userEntry: string): boolean {
   const letters = /[A-Z]/;

   if (letters.test(userEntry[0]))
     return true;

   return false;
}

其他语言的 for 循环 将语法更改为您的语言!

//userEntry param as string
//return boolean
oneUppercaseRequired(userEntry: string): boolean {
   const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

   for (let i = 0; i < letters.length; i++) {
     if (userEntry[0] == letters[i])
       return true;
   }

   return false;
}

Typescript

//userEntry input as string
//return boolean
oneUppercaseRequired(userEntry: string): boolean {
   const letters = /[A-Z]/;

   if (letters.test(userEntry[0]))
     return true;

   return false;
}

for-loop for other languages Change the syntax to your language!

//userEntry param as string
//return boolean
oneUppercaseRequired(userEntry: string): boolean {
   const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

   for (let i = 0; i < letters.length; i++) {
     if (userEntry[0] == letters[i])
       return true;
   }

   return false;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文