How to solve this problem with JS?

0 like 0 dislike
3 views
Could you tell me the direction,not necessarily the full solution to write,just don't understand how to do the task .

The user enters a string, you need to determine
whether it is a palindrome. (A palindrome is a text that
which reads the same left and right.
Examples for testing:
1) '49094' is the string a palindrome
2) 'I would change the world, but God does not give the source' is a string not a palindrome
3) 'Villages in the lake birch forest' is a string a palindrome
by | 3 views

4 Answers

0 like 0 dislike
The easiest way to compare a string with a string Vice-versa. For example, it was "string", and the second line "aborts", and if they are equal (you need to compare in lowercase toLowerCase), the word is a palindrome, if not, then not a palindrome.
UPD: Also you can trim the blanks to the third example worked.
by
0 like 0 dislike
Go around the loop line to the middle, comparing the symbol with the corresponding symbol from the end.

for (let i = 0; i < string.length / 2; i++)

To obtain the character string[i] how to obtain the corresponding from the end, calculate the index yourself.

Enter the string you can use
let string = prompt("Enter something:")
by
0 like 0 dislike
1. To compare the characters of string beginning and the end of the line an equal distance on cycle.
2. In case of any discrepancy (error), exit the loop (the string is not a palindrome), otherwise it is a palindrome.
by
0 like 0 dislike
palindromeChecker function(str) { str = str.toLowerCase().replace(/[^a-za-z1-9]/gi, "); const lastIndex = str.length - 1; for (let i = 0; i < str.length / 2; i++) { if (str[i] !== str[lastIndex - i]) { return false; } } return true; }

palindromeChecker2 function(str) { str = str.toLowerCase().replace(/[^a-za-z1-9]/gi, "); const halfOfLength = Math.floor(str.length / 2); return str.substr(0, Math.floor(halfOfLength)) === str.substr(Math.floor(str.length % 2 ? halfOfLength + 1 : halfOfLength)).split(").reverse().join(") }
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
33,568 users