Palindrome Check in javascript but with while loop - javascript

I am trying to make a palindrome checker with the condition of having to use a while loop.
It's giving me a right headache!
it returns isPalindrome as false every time even if the word is a palindrome.
let word = prompt('Please Enter a word')
let reverse = word.split('').reverse().join('').toLowerCase();
i = 0
final = word.length
let isPalindrome = false
while (i < word.length) {
if(word[i] == reverse[i])
i++
if(i = word.length)
break;
else if (i !== word.length)
break;
}
if (i == word.length) {
isPalindrome == true
}
else if (true) {
isPalindrome == false
}
if (isPalindrome == true) {
window.alert('Your word is a palindrome')
}
else if (isPalindrome == false) {
window.alert('Your word is not a palindrome')
}
I have tried messing around with the == signs and changing the break;
it used to return as always palindrome, but now it always returns as not a palindrome
The idea is to compare the word with the reverse version of it and check every index to see if it matches.
If they all match the word is a palindrome (racecar && racecar)
If they do not match it is not (racer && recar)
The program should output the result
Many thanks!

Alternative: nibble off letters of the word from both sides and compare them until either there's one letter left (is palindrome) or they don't match (no palindrome):
const isPalindrome = word => {
const letters = word.toLowerCase().split("");
while (letters.length > 1) {
if (letters.shift() !== letters.pop()) {
// not a palindrome: break the loop
// by returning false
return false;
};
}
return true;
}
console.log(`racecar ${isPalindrome(`racecar`)}`);
console.log(`rotator ${isPalindrome(`rotator`)}`);
console.log(`carrace ${isPalindrome(`carrace`)}`);
console.log(`rotonda ${isPalindrome(`rotonda`)}`);

Related

check the alphabetical order

I am a newbie who is trying hard to have a grip on javascript. please help me to consolidate my fundamentals.
input will be a string of letters.
following are the requirements.
function should return true if following conditions satisfy:
letters are in alphabetical order. (case insensitive)
only one letter is passed as input. example :
isAlphabet ('abc') === true
isAlphabet ('aBc') === true
isAlphabet ('a') === true
isAlphabet ('mnoprqst') === false
isAlphabet ('') === false
isAlphabet ('tt') === false
function isAlphabet(letters) {
const string = letters.toLowerCase();
for (let i = 0; i < string.length; i++) {
const diff = string.charCodeAt(i + 1) - string.charCodeAt(i);
if (diff === 1) {
continue;
} else if (string === '') {
return false;
} else if (string.length === 1) {
return true;
} else {
return false;
}
}
return true;
}
It's generally a better practice to start your function off with dealing with the edge-cases rather than putting them somewhere in the middle. That way, the function returns as soon as it can - and it's a lot easier to read than a waterfall of if..else statements.
function isAlphabet(letters) {
if ("" == letters) {
return false;
}
if (1 == letters.length) {
return true;
}
const string = letters.toLowerCase();
// carry on with your loop here.
}
You've got the right idea, but it can be simplified to just fail on a particular error condition, i.e when a smaller character follows a larger one:
function isAlphabet(letters) {
const string = letters.toLowerCase();
let lastChar;
for (let i = 0; i < string.length; i++) {
// Grab a character
let thisChar = string.charCodeAt(i);
// Check for the failure case, when a lower character follows a higher one
if (i && (thisChar < lastChar)) {
return false;
}
// Store this character to check the next one
lastChar = thisChar;
}
// If it got this far then input is valid
return true;
}
console.log(isAlphabet("abc"));
console.log(isAlphabet("aBc"));
console.log(isAlphabet("acb"));
You can use the simple way to achieve the same as below
function isAlphabet(inputString)
{
var sortedString = inputString.toLowerCase().split("").sort().join("");
return sortedString == inputString.toLowerCase();
}
console.log("abc = " + isAlphabet("abc"));
console.log("aBc = " + isAlphabet("aBc"));
console.log("acb = " + isAlphabet("acb"));
console.log("mnoprqst = " + isAlphabet("mnoprqst"));
Note: Mark the answer is resolves your problem.

Else if statements with toUpperCase(), toLowerCase() and Number.isInteger() [duplicate]

How can I test if a letter in a string is uppercase or lowercase using JavaScript?
The answer by josh and maleki will return true on both upper and lower case if the character or the whole string is numeric. making the result a false result.
example using josh
var character = '5';
if (character == character.toUpperCase()) {
alert ('upper case true');
}
if (character == character.toLowerCase()){
alert ('lower case true');
}
another way is to test it first if it is numeric, else test it if upper or lower case
example
var strings = 'this iS a TeSt 523 Now!';
var i=0;
var character='';
while (i <= strings.length){
character = strings.charAt(i);
if (!isNaN(character * 1)){
alert('character is numeric');
}else{
if (character == character.toUpperCase()) {
alert ('upper case true');
}
if (character == character.toLowerCase()){
alert ('lower case true');
}
}
i++;
}
if (character == character.toLowerCase())
{
// The character is lowercase
}
else
{
// The character is uppercase
}
The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase.
I found this to work very well for it:
function isLowerCase(str)
{
return str == str.toLowerCase() && str != str.toUpperCase();
}
This will work for punctuation, numbers and letters:
assert(isLowerCase("a"))
assert(!isLowerCase("Ü"))
assert(!isLowerCase("4"))
assert(!isLowerCase("_"))
To check one letter just call it using isLowerCase(str[charIndex])
const isUpperCase = (string) => /^[A-Z]*$/.test(string)
then :
isUpperCase('A') // true
isUpperCase('a') // false
This will log true if character is uppercase letter, and log false in every other case:
var letters = ['a', 'b', 'c', 'A', 'B', 'C', '(', ')', '+', '-', '~', '*'];
​​​for (var ​i = 0; i<letters.length; i++) {
if (letters[i] === letters[i].toUpperCase()
&& letters[i] !== letters[i].toLowerCase()) {
console.log(letters[i] + ": " + true);
} else {
console.log(letters[i] + ": " + false);
}
}​
You may test it here: http://jsfiddle.net/Axfxz/ (use Firebug or sth).
​​​for (var ​i = 0; i<letters.length; i++) {
if (letters[i] !== letters[i].toUpperCase()
&& letters[i] === letters[i].toLowerCase()) {
console.log(letters[i] + ": " + true);
} else {
console.log(letters[i] + ": " + false);
}
}​
and this is for lowercase:).
function isUpperCase(myString) {
return (myString == myString.toUpperCase());
}
function isLowerCase(myString) {
return (myString == myString.toLowerCase());
}
You could utilize a regular expression test and the toUpperCase method:
String.prototype.charAtIsUpper = function (atpos){
var chr = this.charAt(atpos);
return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
};
// usage (note: character position is zero based)
'hi There'.charAtIsUpper(3); //=> true
'BLUE CURAÇAO'.charAtIsUpper(9); //=> true
'Hello, World!'.charAtIsUpper(5); //=> false
See also
function isCapital(ch){
return ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90;
}
More specifically to what is being asked. Pass in a String and a position to check. Very close to Josh's except that this one will compare a larger string. Would have added as a comment but I don't have that ability yet.
function isUpperCase(myString, pos) {
return (myString.charAt(pos) == myString.charAt(pos).toUpperCase());
}
function isLowerCase(myString, pos) {
return (myString.charAt(pos) == myString.charAt(pos).toLowerCase());
}
A good answer to this question should be succinct, handle unicode correctly, and deal with empty strings and nulls.
function isUpperCase(c) {
return !!c && c != c.toLocaleLowerCase();
}
This approach deals with empty strings and nulls first, then ensures that converting the given string to lower case changes its equality. This ensures that the string contains at least one capital letter according to the current local's capitalisation rules (and won't return false positives for numbers and other glyphs that don't have capitalisation).
The original question asked specifically about testing the first character. In order to keep your code simple and clear I'd split the first character off the string separately from testing whether it's upper case.
You can also use a regular expression to explicitly detect uppercase roman alphabetical characters.
isUpperCase = function(char) {
return !!/[A-Z]/.exec(char[0]);
};
EDIT: the above function is correct for ASCII/Basic Latin Unicode, which is probably all you'll ever care about. The following version also support Latin-1 Supplement and Greek and Coptic Unicode blocks... In case you needed that for some reason.
isUpperCase = function(char) {
return !!/[A-ZÀ-ÖØ-ÞΆΈ-ΏΑ-ΫϢϤϦϨϪϬϮϴϷϹϺϽ-Ͽ]/.exec(char[0]);
};
This strategy starts to fall down if you need further support (is Ѭ uppercase?) since some blocks intermix upper and lowercase characters.
There's a really simple answer, which nobody else has mentioned:
function isLowerCase(str) {
return str !== str.toUpperCase();
}
If str.toUpperCase() does not return the same str, it has to be lower case. To test for upper case you change it to str !== str.toLowererCase().
Unlike some other answers, it works correctly on non-alpha characters (returns false) and it works for other alphabets, accented characters etc.
This is straightforward, readable solution using a simple regex.
// Get specific char in string
const char = string.charAt(index);
const isLowerCaseLetter = (/[a-z]/.test(char));
const isUpperCaseLetter = (/[A-Z]/.test(char));
I believe this is the easiest solution.. You can use onchange handler in input field .. to do the validation
const isValid = e.target.value === e.target.value.toLowerCase()
if (isValid) {
//Do something
} else {
//Do something
}
With modern browsers you can use regexp and unicode property tests e.g.
/\p{Lu}/u.test("A") // is true
/\p{Lu}/u.test("Å") // is true
/\p{Lu}/u.test("a1å") // is false
More info here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes
List of general categories here:
https://unicode.org/reports/tr18/#General_Category_Property
You can also use this, it will check the string for lower and uppercase
var s = "a"
if(/[a-z]/.test(s)){
alert ('lower case true');
}
if(/[A-Z]/.test(s)) {
alert ('upper case true');
}
The best way is to use a regular expression, a ternary operator, and the built in .test() method for strings.
I leave you to Google the ins and outs of regular expressions and the test method for strings (they're easy to find), but here we'll use it to test your variable.
/[a-z]/i.test(your-character-here)
This will return TRUE of FALSE based on whether or not your character matches the character set in the regular expression. Our regular expression checks for all letters a-z /[a-z]/ regardless of their case thanks to the i flag.
So, a basic test would be:
var theAnswer = "";
if (/[a-z]/i.test(your-character-here)) {
theAnswer = "It's a letter."
}
Now we need to determine if it's upper or lower case. So, if we remove the i flag from our regular expression, then our code above will test for lower case letters a-z. And if we stick another if statement in the else of our first if statement, we can test for upper case too by using A-Z. Like this:
var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
theAnswer = "It's an upper case letter.";
}
And just in case it's not a letter, we can add a final else statement:
var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
theAnswer = "It's an upper case letter.";
} else {
theAnswer = "It's not a letter."
}
The above code would work. But it's kinda ugly. Instead, we can use a "ternary operator" to replace our if-else statements above. Ternary operators are just shorthand simple ways of coding an if-else. The syntax is easy:
(statement-to-be-evaluated) ? (code-if-true) : (code-if-false)
And these can be nested within each other, too. So a function might look like:
var theAnswer = "";
function whichCase(theLetter) {
theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : "";
theAnswer = /[A-Z]/.test(theLetter) ? "It's upper case." : "";
return(theAnswer);
}
The above code looks good, but won't quite work, because if our character is lower case, theAnswer gets set to "" when it test for uppercase, so lets nest them:
var theAnswer = "";
function whichCase(theLetter) {
theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : (/[A-Z]/.test(theLetter) ? "It's upper case." : "It's not a letter.");
return(theAnswer);
}
That will work great! But there's no need to have two seperate lines for setting the variable theAnswer and then returning it. And we should be using let and const rather than var (look those up if you're not sure why). Once we make those changes:
function whichCase(theLetter) {
return(/[A-Z]/.test(theLetter) ? "It's upper case." : (/[a-z]/.test(theLetter) ? "It's lower case." : "It's not a letter."));
}
And we end up with an elegant, concise piece of code. ;)
See my comment on the chosen answer. Other solutions that limit to the ASCII table or use the actual character literals completely ignore Unicode and the several hundred other characters there that have case.
This code will set the caseGroup variable to:
1 for Upper Case
-1 for Lower Case
0 for Without Case
var caseGroup = (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
You could bake that into something like this...
function determineCase(character) {
return (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
}
function isUpper(character) {
return determineCase(character) == 1;
}
function isLower(character) {
return determineCase(character) == -1;
}
function hasCase(character) {
return determineCase(character) != 0;
}
function solution(s) {
var c = s[0];
if (c == c.toUpperCase() && !(c >= '0' && c <= '9') &&(c >='A' && c <= 'Z')) {
return 'upper';
} else if (c == c.toLowerCase() && !(c >= '0' && c <= '9') &&(c >='a' && c <= 'z')){
return 'lower';
} else if (c >= '0' && c <= '9'){
return 'digit'
} else {
return 'other'
}
}
var str1= (solution('A')) // upper
var str2 = solution('b') // lower
var str3 = solution('1') // digit
var str4 = solution('_') // other
console.log(`${str1} ${str2} ${str3} ${str4}`)
You can test if your array has an upper case or lower case string by using the match method and regex, below is just a basic foundation to start your test
var array = ['a', 'b', 'c', 'A', 'B', 'C', '(', ')', '+', '-', '~', '*'];
var character = array.join('')
console.log(character)
var test = function(search){
upperCase = search.match(/[A-Z]/g)
console.log(upperCase)
lowerCase = search.match(/[a-z]/g)
console.log(lowerCase)
}
test(character)
This is how I did it recently:
1) Check that a char/string s is lowercase
s.toLowerCase() == s && s.toUpperCase() != s
2) Check s is uppercase
s.toUpperCase() == s && s.toLowerCase() != s
Covers cases where s contains non-alphabetic chars and diacritics.
function checkCharType (charToCheck) {
// body...
var returnValue = "O";
var charCode = charToCheck.charCodeAt(0);
if(charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)){
returnValue = "U";
}else if (charCode >= "a".charCodeAt(0) &&
charCode <= "z".charCodeAt(0) ){
returnValue = "L";
}else if (charCode >= "0".charCodeAt(0) &&
charCode <= "9".charCodeAt(0) ) {
returnValue = "N";
}
return returnValue;
}
var myString = prompt("Enter Some text: ", "Hello world !");
switch (checkCharType(myString)) {
case "U":
// statements_1
document.write("First character was upper case");
break;
case "L":
document.write("First character was a lower case");
break;
case "N":
document.write("First character was a number");
break
default:
// statements_def
document.write("First character was not a character or a number");
break;
}
Define a Function checkCharType().By declaring the variable returnValue and initialising it to the Character "O" to indicate it's Some other value.
U for uppercase; L for Lowercase ; N for number
Use the charCodeAt() method to get the character code of the first character.
Using if Statement , which check within what range of values the character code falls.
If it falls between the character codes for A and Z, Its Uppercase,
character code between a and z ,Its Lowercase. and so on.
"A".charCode(0)
var myChar = new String("A");
myChar.charCodeAt(0);
"A" : number code "65“
Check the String
This checks the ENTIRE string, not just the first letter. I thought I'd share it with everyone here.
Here is a function that uses a regular expression to test against the letters of a string; it returns true if the letter is uppercase (A-Z). We then reduce the true/false array to a single value. If it is equal to the length of the string, that means all the letters passed the regex test, which means the string is uppercase. If not, the string is lowercase.
const isUpperCase = (str) => {
let result = str
.split('')
.map(letter => /[A-Z]/.test(letter))
.reduce((a, b) => a + b);
return result === str.length;
}
console.log(isUpperCase('123')); // false
console.log('123' === '123'.toUpperCase()); // true
This question has clearly been answered a number of times, but i thought i'd share my solution as I haven't seen it in the given answers.
var lower_case = function(letter){
lowers = "abcdefghijklmnopqrstuvwxyz";
return letter === letter.toLowerCase() && lowers.indexOf(letter) >= 0
};
var upper_case = function(letter){
uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return letter === letter.toUpperCase() && uppers.indexOf(letter) >= 0
};
2¢
function checkCase(c){
var u = c.toUpperCase();
return (c.toLowerCase() === u ? -1 : (c === u ? 1 : 0));
};
Based on Sonic Beard comment to the main answer. I changed the logic in the result:
0: Lowercase
1: Uppercase
-1: neither
Assuming that a string is only considered to not be all uppercase if at least one lowercase letter is present, this works fine. I understand it's not concise and succinct like everybody else tried to do, but does it works =)
function isUpperCase(str) {
for (var i = 0, len = str.length; i < len; i++) {
var letter = str.charAt(i);
var keyCode = letter.charCodeAt(i);
if (keyCode > 96 && keyCode < 123) {
return false;
}
}
return true;
}
I need to test against a string of any character (including white space, marks, numbers, unicode characters...). Because white space, numbers, marks... will be the same in both upper case and lower case, and I want to find real upper case letters, I do this:
let countUpperCase = 0;
let i = 0;
while (i <= string.length) {
const character = string.charAt(i);
if (character === character.toUpperCase() && character !== character.toLowerCase()) {
countUpperCase++;
}
i++;
}
Simply check the ASCII value
// IsLower verify that a string does not contains upper char
func IsLower(str string) bool {
for i := range str {
ascii := int(str[i])
if ascii < 91 && ascii > 64 {
return false
}
}
return true
}
Another way is to compare the character with an empty object, i don't really know's why it works, but it works :
for (let i = 1; i <= 26; i++) {
const letter = (i + 9).toString(36).toUpperCase();
console.log('letter', letter, 'is upper', letter<{}); // returns true
}
for (let i = 1; i <= 26; i++) {
const letter = (i + 9).toString(36);
console.log('letter', letter, 'is upper', letter<{}); // returns false
}
so in a function :
function charIsUpper(character) {
return character<{};
}
EDIT: it doesn't work with accents and diacritics, so it's possible to remove it
function charIsUpper(character) {
return character
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')<{};
}
One I use (notice this doesnt make "TestString" as "T est String" or " Test String").
function seperateCapitalised(capitalisedString) {
if (typeof capitalisedString !== "string" || capitalisedString.length === 0)
return capitalisedString;
var newStr = capitalisedString[0];
for (var i = 1; i < capitalisedString.length; i++) {
var char = capitalisedString[i];
if (char === char.toUpperCase() && isNaN(char)) {
newStr += ' ' + char;
}
else {
newStr += char;
}
}
return newStr;
}

JavaScript See if word contains ordered increasing/decreasing chars and repeat

2 codebase were written for checking string.
-The first is to confirm if a string contains 3 or more repeated characters in a string(111, ***, sss).
-The second if the string contains 3 or more ordered characters (123, efg, nml, 654). Ordered string checks if numbers or letters are in order of ascending or descending char.
Are there any edge cases I should worry about? Any way to optimize either? I want to keep these 2 algorithms separate.
//code for consecutive repeated character
const str= 'adsas111';//return true since 111 is repeated
let count=1;
for (let i = 0; i < str.length-1; i++) {
if(str.charAt(i) === str.charAt(i+1)) count++;
else if(count <3) count =1
if(count === 3) return console.log('It is repeated');
}
//code for consecutive ordered character
const str= 'adsa!"#32112s11'; // return true since 321 is repeated
let ascCount=1;
let descCount=1
let len=str.length-1;
for (let i = 0; i < str.length-1; i++) {
if((str.charCodeAt(i)>=97 && str.charCodeAt(i)<=122) || (str.charCodeAt(i)>=48 && str.charCodeAt(i)<=57)) {
if(str.charCodeAt(i)+1 === str.charCodeAt(i+1)) ascCount ++;
else if(ascCount <3) ascCount =1
if(str.charCodeAt(len--)+1 === str.charCodeAt(len)) descCount ++;
else if(descCount <3) descCount =1
if(ascCount === 3 || descCount === 3) return console.log('is in order');
}
}

node.js – Check if word has an added/changed letter to a previous word

I'm working on a command for my Discord bot that allows for a game to be played, in which the goal is to post words that either change one letter in the previous word, or add a letter. I'm using this function:
function checkDifferentString(str1, str2) {
let diff = 0;
if (str1 === str2) return true;
let lengthDiff = Math.abs(str1.length - str2.length)
if (lengthDiff > 1) return false;
for (let i=0; (i<str1.length || i < str2.length);i++) {
if (diff > 1) return false;
if (str1.charAt(i) !== str2.charAt(i)) diff++
}
if (diff <= 1) return true
else return false;
}
and it works fine if you change a letter, or add a letter to the end of the word (e.g. mat->math). But if you add a letter in the word (e.g. mat->malt), it says that the word doesn't follow the rules, even though it does. How can I change the function so it also catches for added letters inside the words?
I think this is more easier to understand.
function isChanged(prev, curr) {
return (prev.length + 1 === curr.length && curr.slice(0, prev.length) === prev)
|| (prev.length === curr.length && Array.from(prev).filter((ch, idx) => ch != curr[idx]).length === 1)
}
The first condition is true when add one character.
The second conditions is true when there is only one different character.
Updated (I did misread your question)
To check change one letter, use longest common sequence(https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
If two string has same length N and the length of longest common sequence is N-1, it means one letter is changed.
If two string has length N and N+1, and the length of longest common sequesnce is N, it means one letter is added.
function lengtOfLCS(s1, s2) {
// LCS algorithm..
return result
}
function isChanged(prev, curr) {
return (prev.length === curr.length && lengtOfLCS(prev, curr) === prev.length - 1)
|| (prev.length+1 === curr.length && LCSlengtOfLCSprev, curr) === prev.length)
}

find multiple (2) elements in a string in javascript

I want to return whether one of the conditions exist within findAB(str) as boolean
A 5 letter long string which starts with 'a' ends with 'b'
A 5 letter long string which starts with 'b' ends with 'a'
function findAB(str) {
let lowerSTR = str.toLowerCase()
let indexOFa = lowerSTR.indexOf('a')
let indexOFb = lowerSTR.indexOf('b')
if (lowerSTR[indexOFa + 4] === 'b' || lowerSTR[indexOFb + 4] === 'a') {
return true;
}
return false;
}
I first changed strings into lower case using .toLowerCase() method and defined indexOFa and indexOFb.
I thought simply by doing index of a + 4 will turn out true but in fact it doesn't and cannot figure out what I did wrong.
I also know some method to find elements in an array such as find(), includes(), map() or filter but not sure if I can use it since it is not an array.
If you want to change your approach you can use regex like this
function findAB(str) {
let case1 = str.match(/a[a-z]*b/g); // get all substrings starting with a and ending with b
let case2 = str.match(/b[a-z]*a/g); // get all substrings starting with b and ending with a
case1.forEach((matchedString) => {
if (matchedString.length == 5) {
return true;
}
});
case2.forEach((matchedString) => {
if (matchedString.length == 5) {
return true;
}
});
return false; // return false if no substrings matching condition exists
}
If you need to tell the difference between which case was triggered this could be a cleaner solution to read.
If you want to search for a pattern of 5 characters which starts and ends with (a and b) or (b and a) irrespective of case and any length of string, you can do something like this.
The regex considers that the string "a _ _ _ b" or "b _ _ _ a" can have only alphabets in any case not any other character, if you are accepting any other character you can update [a-zA-Z] part in the regex.
function findAB(str) {
const regexp = /(.?(((a|A)[a-zA-Z]{3}(b|B))|((b|B)[a-zA-Z]{3}(a|A))).?)/;
return regexp.test(str);
}
If it is fixed that length of string should be 5 and you are just dealing with first and last character you can simply use the following function
function findAB(str) {
const lengthOfString = str.length;
if (lengthOfString === 5) {
const firstCharacter = str[0].toLowerCase()
const lastCharacter = str[lengthOfString-1].toLowerCase()
return (firstCharacter === 'a' && lastCharacter === 'b') || (firstCharacter === 'b' && lastCharacter === 'a');
}
// returns false string does not contains 5 characters
return false;
}
Correcting your solution.
The problem with your solution is that indexOf returns -1 if the no match is found. So findAB("bbbbb") will return true, because indexOFa variable will be equal to -1 and lowerSTR[indexOFa + 4] will check the second last character and the condition will evaluate to true. So the following code will solve your problem.
function findAB(str) {
let lowerSTR = str.toLowerCase()
let indexOFa = lowerSTR.indexOf('a')
let indexOFb = lowerSTR.indexOf('b')
if ((indexOFa >= 0 && lowerSTR[indexOFa + 4] === 'b') || (indexOFb >= 0 && lowerSTR[indexOFb + 4] === 'a')) {
return true;
}
return false;
}
Also, I wouldn't prefer hardcoding 4 better use str.length-1.
You could also just simply do it like this
function findAB(str) {
let lowerSTR = str.toLowerCase();
let indexOFa = lowerSTR.indexOf('a');
let indexOFb = lowerSTR.indexOf('b');
if (
(indexOFa === 0 && indexOFb === str.length - 1) ||
(indexOFb === 0 && indexOFa === str.length - 1)
)
return true;
return false;
}

Categories

Resources