faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

Entry

how would I write a sript to find wheather a word is palindrome

Apr 8th, 2008 19:18
ha mo, Dave Clark, Matt Chatterley, prerna bk,


Basically, you need to:
1. Store the value to check in a variable
2. Store the string-reversal of the value in another variable
3. Compare the two strings to see if they are the same.
You can active #2 by writing a simple javascript function which steps
through every character in a given string, starting the with last one
(string.length -1), through the first one (0), and adding them to a new
string value.
Then using the Regexp class (and/or the string.match) function, you can
compare the two, and return the result.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prema,
     Here's another way:
var str = "A man, a plan, a canal, Panama!";
//
var len, str = str.toLowerCase().replace(/[^a-z]/g, '');
var x, half = Math.ceil((len = str.length) / 2);
for (x=0; x<half; ++x)
{
    if (str.substr(x,1) != str.substr(len-1-x,1)) break;
}
if (x < half)
  alert('String is not a palindrome.');
else
  alert('String is a palindrome.');
Take care,
Dave Clark
www.DaveClarkConsulting.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com