我正在编写一个将字符串作为参数的函数。然后如果字符串以大写字母开头,则返回true,否则返回false。但是我当前的函数只适用于一个单词字符串,我希望它同时适用于一个单词和一个完整的句子。如何改进我的代码以实现这一目标?其次,当数字在句子中传递时,它不应该工作。我怎样才能做到这一点?
这是我的代码
function takeString (str) {
var regex = /^[A-Za-z]+$/;
if (str.match(regex)) {
if (str.charAt(0) === str.toUpperCase().charAt(0)) {
alert('true');
return true;
} else {
alert('false');
return false;
}
} else {
alert('Only letters please.');
}
}
takeString('This is'); // shows Only letters please which is wrong. this should work
takeString('String); // returns true which right
takeString('string'); // returns false which is right
takeString('This is 12312321'); // shows only letters please which is right bcoz it has digits
takeString('12312312'); // show Only letters please which is right.
</p>