Hi all,
today i thought id write a function to see if a string is a palindrome "a word which is spelt the same when read backwards"
and thought id post it on here, to see what other/better ways you guys had of doing it or even though i think my code works, maybe some of you see some bugs i dont know about.

anyways never posted on here before even though i have been registered for a while

<html>
	<head>
		<script type='text/javascript'>
			function handler() {
				var string = document.getElementById('string').value;
				if (true == isPalindrome(string)) {
					alert(string + ": is a palindrome");
				} else {
					alert(string + ": is not a palindrome");
				}
			}
			function isPalindrome(string) {
				if (string.length <= 1) {
					return true;
				} else if (string.charAt(0) == string.charAt(string.length-1)) {
					string = string.substring(1, string.length-1);
					return isPalindrome(string);
				} else {
					return false;
				}
			}
		</script>
	</head>
	<body>
		<button onclick='handler()'>call</button>
		<br />
		<input type='text' id='string' />
	</body>
</html>

anyways all feedback welcome

PS. i got started on this after watching a lecturer do it in python, heres the link
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/video-lectures/lecture-4/
and jump to 42:40 on the time index

function isPalindrome(str) {
	return (
		str.length <= 1 ||
		(str = str.toLowerCase()) ==
		str.split('').reverse().join('')
	);
}

alert(isPalindrome('RaceFastSafeCar')); // Returns true

In your method you have not set the variable to lowercase, so words that start with a capital will always return false.

Also, having a reoccurring function like that is not very efficient. It's better to make an array out of the strings characters, reverse the array, and rejoin the string.

Thanks for your reply benjamin I wanted to use a recurring function "initially" to learn how they work, I like your solution to the problem, and yes capitals would come back false :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.