Check if first character of a string is a letter in JavaScript - 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 SearchingChallenge = str => (
!!str[4] && // > 4
!str[24] && // < 25
(/^[a-z]+$/i).test(str) // alpha
);
// Tests...
// true: greater than four characters
console.log(SearchingChallenge('Fiver'));
// true: less than twenty-five characters
console.log(SearchingChallenge('TwentyFouroooooooooooooo'));
// false: twenty-five or more characters
console.log(SearchingChallenge('TwentyFiveooooooooooooooo'));
// false: contains numbers
console.log(SearchingChallenge('abcd1234'));
// false: less than five characters
console.log(SearchingChallenge('Four'));

Related

Why does function return undefined when it explicitly is told to return true?

I was trying to solve the following coding exercise.
We have two special characters. The first character can be represented
by one bit 0. The second character can be represented by two bits (10
or 11).
Now given a string represented by several bits. Return whether the
last character must be a one-bit character or not. The given string
will always end with a zero.
example:
Input: bits = [1, 0, 0] Output: True
Below is my solution for the above challenge. Why is this returning undefined? If I use [1,0,1,0] as input, it should return true but I am getting undefined. I am explicitly writing true in the return statement and not the results of a variable.
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
isOneBitCharacter(bits.slice(1));
} else {
isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);
I guess you are missing returns. Here is adjusted code:
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
// added return here and next statements
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
return isOneBitCharacter(bits.slice(1));
} else {
return isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);

Validate Credit card without regExp

I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}

isNan help in an if else statement

I am doing an online exercise and I am required to use an if else statement. The isNaN statement is not working. I am required to return a string if the input of number is not an actual number. This won't compile please help:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (number % 2 !== 0) {
return false;
} else if (isNaN(number)) {
return "you need to enter a number";
} else {
return false;
}
};
Your code returns false because of
else if (number % 2 !== 0)
line, So check isNaN before everything like so
var isEven = function(number) {
if (isNaN(number)) {
return "you need to enter a number";
} else {
if (number % 2 === 0){
return true;
} else if (number % 2 !== 0) {
return false;
}
}
};
console.log(isEven(NaN));
you need to enter a number
You need to have isNan as first check in you if-else-if condition.
Explanation:
If the argument is not a number, then number % 2 !== 0 will be true and it will return the value.
Note:
return statement, terminates the execution of the function further and returns the value. So, even if-else-if is not required here.
and beware with Booleans in NaN and empty string.
Example Snippet:
var isEven = function(number) {
if (isNaN(number)) {
return "you need to enter a number";
}
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
console.log(isEven(2));
console.log(isEven(3));
console.log(isEven('i am not a number'));
console.log(isEven(true));

Determining the case (upper/lower) of the first letter in a string

In a web application, how do I determine whether the first letter in a given string is upper- or lower-case using JavaScript?
You can use toUpperCase:
if(yourString.charAt(0) === yourString.charAt(0).toUpperCase()) {
//Uppercase!
}
If you're going to be using this on a regular basis, I would suggest putting it in a function on the String prototype, something like this:
String.prototype.isFirstCapital = function() {
return this.charAt(0) === this.charAt(0).toUpperCase();
}
if(yourString.isFirstCapital()) {
//Uppercase!
}
Update (based on comments)
I don't know what you actually want to do in the case that the string does not being with a letter, but a simple solution would be to add a quick check to see if it does or not, and return false if not:
String.prototype.isFirstCapital = function() {
return /^[a-z]/i.test(this) && this.charAt(0) === this.charAt(0).toUpperCase();
}
This will work only with English alphabet.
var ch = myStr.chatAt(0);
if (ch >= 'a' && ch <= 'z') {
// small
} else if (ch >= 'A' && ch <= 'Z') {
// capital
} else {
// not english alphabet char
}
var mystring = "Test string";
var first= "";
if (mystring )
{
first= mystring[1];
}
if (first)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() === $(this).text().charAt(0))
{
alert("Uppercase");
}
});
}
This will be called recursively until a first letter in a string is approached, otherwise returns 'no letters'.
function getFirstCase(string) {
if (string === '') return 'no letters';
var firstChar = string.charAt(0);
/*
* If both lowercase and uppercase
* are equal, it is not a letter
*/
if (firstChar.toLowerCase() === firstChar.toUpperCase()) {
return getFirstCase(string.substr(1));
} else {
return firstChar.toLowerCase() === firstChar ? 'lowercase' : 'uppercase';
}
}
Testing:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
I'm surprised no one's offered a regex solution to this - it seems like the easiest by far:
function getFirstCase(s) {
return (/^[\d\W]*[A-Z]/).test(s) ? 'upper' :
(/^[\d\W]*[a-z]/).test(s) ? 'lower' :
'none';
}
Blatantly stealing #Lapple's test cases:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
// lower upper none upper upper
See http://jsfiddle.net/nrabinowitz/a5cQa/

checking for integer input on button click

I am trying to get this Javascript in my application working.
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
return true;
}
}
And I have a input button as below
<input class="buttonToLink" type="submit" value="Update"
onclick="return validateQuantity(document.getElementById('quantity'))"/>
The above code successfully checks the input of all alphabet such as "abc" or alphabet and numeric such as "abcd123" as false.
However, when I put numeric characters first, along with alphabet such as "123abc", it fails -- it does not show the alert.
What did I do wrong with the code, and how can it be fixed?
function validateQuantity(field) {
if (!/^\d+$/.test(field.value)) { // is an integer
alert("Please enter number and greater than 0 only");
return false;
}
return true;
}
The reason your code doesn't work is because you have the return true statement inside the loop. As soon as it sees a valid integer it will return true and break out of the function, ignoring anything that comes after it. Allowing strings like "123abc" for example.
This is probably what you wanted:
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
}
return true;
}
if (parseInt(new_Key) == new_Key) {
//valid
} else { // it will return NaN
//invalid
}
Try parsing the value as an integer, and compare with the original value.
var isAllNumbers = (parseInt(field.value) == field.value);
Perhaps use a jQuery selector, and use a regex to test for numeric.
var isAllNumbers = $("#quantity").val().match(/\d+$/);

Categories