简体   繁体   中英

Check if first character of a string is a letter in JavaScript

I'm trying to write a function that checks a string for multiple conditions. However, I have reached a wall when trying to figure out how to check if the first character in a string is a letter only.

function SearchingChallenge(str) { 

// code goes here  
let onlyLetters = /^[a-zA-Z]+$/;

if (str.length > 4 && str.length < 25){
  if (onlyLetters.test(str)){
  return true;
} else {
  return false;
}
} else {
return false;
}
}

"u__adced_123" should return true but it's returning false. I've tried str[0]==onlyLetters but still the same.

onlyLetters.test(str) checks the whole string. To get the first character, use str.charAt(0) .

 function SearchingChallenge(str) { let onlyLetters = /^[a-zA-Z]+$/; if (str.length > 4 && str.length < 25) { if (onlyLetters.test(str.charAt(0))) { return true; } else { return false; } } else { return false; } } console.log(SearchingChallenge('Hello World!')); console.log(SearchingChallenge('!dlroW olleH')); console.log(SearchingChallenge('u__adced_123'));

 const onlyLetters = /[a-zA-Z]/; function SearchingChallenge(str) { // code goes here return ( str.length > 4 && str.length < 25 && onlyLetters.test(str[0]) ); } console.log(SearchingChallenge('abcde')); console.log(SearchingChallenge('1234')); console.log(SearchingChallenge('bcdefghijklmnopqrstuvwxy'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM