Javascript 检查单词的第一个字母是否是大写字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8334606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if first letter of word is a capital letter
提问by James J
Is it possible in Javascript to find out if the first letter of a word is a capital letter?
是否可以在 Javascript 中找出单词的第一个字母是否是大写字母?
回答by Gabriele Petrioli
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()
回答by user56reinstatemonica8
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 "Александра".
此页面上的其他答案适用于已知仅包含非重音 AZ 字母的字符串。如果您不能保证这一点(例如用户输入),它们可能会给出意想不到的结果:对于像“1940s”或“中文”这样的非大写首字母的误报,或者像“?ukasz”或“?ukasz”这样的重音或非罗马大写首字母的误报“Александра”。
This variant returns true if the initial is anycapital letter, and onlyif it's a capital letter:
如果首字母是任何大写字母,并且仅当它是大写字母时,此变体返回 true :
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.
如果您需要 IE8 支持,请使用.charAt(0)
代替。哪个更快因浏览器而异。[0]
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ūúnor ?i?-si?. It'll also treat any input from an alphabet that doesn't have capital letters as being capital letters (e.g. 中文).
使用的正
[A-Z]
则表达式将无法匹配重音符号和其他类似的非 AZ 大写字母,例如 ?land(斯堪的纳维亚群岛)和?ukasz(常用波兰语名称),包括非拉丁文字中的大写字母,例如西里尔字母或希腊语(例如Александра) .使用
word[0] === word[0].toUpperCase()
,的方法将对以非字母开头的单词返回 true,例如1940s、17th、123reg(公司名称)、缩写2mrw或某些非洲语言中的某些单词,例如!xūún或?i?-si ? . 它还会将来自没有大写字母的字母表的任何输入视为大写字母(例如中文)。
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???????o?????????', true ); // All pass. Phew, Zalgo not awakened
回答by zurfyx
For Englishletters only:
仅适用于英文字母:
'A' => 65
'Z' => 90
Meaning, every number between [65, 90] is a capital letter:
意思是, [65, 90] 之间的每个数字都是大写字母:
function startsWithCapitalLetter(word) {
return word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90;
}
回答by Mike Christensen
Yes.
是的。
var str = "Hello";
if(str[0].toUpperCase() == str[0])
{
window.alert('First character is upper case.');
}
回答by nnnnnn
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.
请注意,对字符的数组样式访问myWord[0]
是 ECMAScript 5 的一项功能,旧浏览器不支持,因此(目前)我可能会推荐.charAt()方法。
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 */ }
回答by jcroll
Using the match
method of the string object prototype:
使用match
字符串对象原型的方法:
const word = 'Someword';
console.log(word.match(new RegExp(/^[A-Z]/)) !== null);
回答by smnbss
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');