Is it possible in Javascript to find out if the first letter of a word is a capital letter?
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');
Using the match
method of the string object prototype:
const word = 'Someword';
console.log(word.match(new RegExp(/^[A-Z]/)) !== null);
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 */ }
Yes.
var str = "Hello";
if(str[0].toUpperCase() == str[0])
{
window.alert('First character is upper case.');
}
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;
}
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()