www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: palindrome string

  1. #1
    Join Date
    Mar 2010
    Posts
    6

    palindrome string

    I am having trouble figuring out how to get this to work properly. Assignment details are in the purpose section.


    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
    <!--Name: Janice Schwartzmeyer
    Date: March 2010
    Class: CST-214-WN310 Java Script Wed 6pm
    Assignment number and title: Palindrome
    Purpose: use for loop in order to test a word inputted by the user
    to see if it is a palindrome. Display word typed and whether or
    not it is a palindrome.

    -->

    <title>Palindrome</title>

    </head>

    <body>
    <script language="JavaScript" type="text/javascript">
    <!--

    //declare s1 as a variable and prompt user for a word
    var s1 = prompt("enter a word");

    //increment and read through it forwards
    for (i=0; i<=s1.length - 1; i++)
    {
    document.write("the letters in the string s1 are: " + s1.charAt(i) + "<br />");
    }

    // feed s1 into s2
    var s2 = s1;

    //decriment and read through it backwards
    for (i = s2.length - 1; i>=0; i--)
    {
    document.write("the letters the other way in the string s1 are: " + s2.charAt(i) + "<br />");
    }
    //var array1[s1]; //try comparing arrays?
    //var array2[s2];

    if (s1 == s2)
    alert( s1 + "is a palindrome")
    else
    alert( s1 + "is not a palindrome")

    /*
    // causes an error
    int i;
    int s2=s1.length();
    String str="";
    for(i=s2-1;i>=0;i--)
    str=str+s1.charAt(i);
    if(str.equals(s1))
    System.out.println(s1+ "is palindrome");
    else
    System.out.println(s1+ "is not a palindrome");
    */

    //-->

    </script>


    </body>
    </html>

  2. #2
    Join Date
    Mar 2010
    Posts
    6
    I did some digging around in the book and found a way to get it to work. It is not perfect but it gives me the desired output. I am still open to a better way of accomplishing this.

    <script type="text/javascript">
    <!--
    //declare s1 as a variable and prompt user for a word
    var s1 = prompt("enter a word");
    s1 = s1.toUpperCase()

    for (i = s1.length - 1; i>=0; i--)
    {
    var s2 = s1;
    }

    document.write(s1.localeCompare(s2));
    if(false)
    alert( s1 + " is a palindrome");
    else
    alert( s1 + " is not a palindrome");
    //-->
    </script>

  3. #3
    Join Date
    Mar 2010
    Posts
    6

    Palindrome string

    Okay it didnt work. I checked it for "not a palindrome" but didn't check it for "is a palindrome"

  4. #4
    Join Date
    Feb 2006
    Posts
    2,927
    Apparently this is an exercise, but where are you getting System.out.println from?
    Last edited by mrhoo; 03-10-2010 at 09:40 PM.

  5. #5
    Join Date
    Mar 2010
    Posts
    6
    What do you mean? the output is shown in a pop up/ alert box. This is supposed to be a simple project. We can use println or alert.

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441

    Exclamation

    Quote Originally Posted by xravensxdreamx View Post
    What do you mean? the output is shown in a pop up/ alert box. This is supposed to be a simple project. We can use println or alert.
    In your original post ...
    Code:
    /*
    // causes an error
    int i;
    int s2=s1.length();
    String str="";
    for(i=s2-1;i>=0;i--)
    str=str+s1.charAt(i);
    if(str.equals(s1))
    System.out.println(s1+ "is palindrome");
    else
    System.out.println(s1+ "is not a palindrome");
    */
    It is commented out, but it appears to be 'java' code, not 'javascript'.
    It will surely cause an error in javascript. That's where the question came from.

    You also do not need to use the <!-- and // --> within the script code for modern browsers.

  7. #7
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441
    Use the 'search this forum' button with 'palindrome' for a number of other examples.

  8. #8
    Join Date
    Mar 2010
    Posts
    6
    I did change the <!-- --> and put in the CDATA. The problem I am currently taking C++ and Java Programming as well. The teacher kinda just threw us to the wolves. He said this is how to do a for loop, this is the if's and else's, and go ahead and code this to test for a palindrome. That is why I am lost. I just need suggestions on how to complete the task in JavaScript. If the issue is that I am coding illegally for JavaScript then how do I accomplish the comparison of two stings? My last attempt was to put them into two arrays but this causes and error. I looked at the other examples and I am getting no where.

    <script type="text/javascript">
    /* <![CDATA[ */
    //declare s1 as a variable and prompt user for a word
    var s1 = prompt("enter a word");
    s1 = s1.toUpperCase() // make word upper case
    var j;
    // reverses the word entered by the user
    for (var i = s1.length - 1; i>=0; i--, j++)
    {
    var s2 = s1; // take word that was reversed and put it in s2
    }
    // turn them into an array
    var arrays = new array();
    var array1[] = s1;
    var array2[] = s2;

    // compare the arrays and display message
    for( var j=0;j<array1.length;j++)
    {
    if(array1[j] == array2[j])
    {
    alert( s1 + " is a palindrome");
    else
    alert( s1 + " is not a palindrome");
    }
    }

    </script>

  9. #9
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441

  10. #10
    Join Date
    Feb 2006
    Posts
    2,927
    <script type="text/javascript">
    Code:
    String.prototype.isaPalindrome= function(){
        var s=this.replace(/\W+/g,'').toLowerCase();
        return s.split('').reverse().join('')== s;
    };
    
    
    var s1= 'ab';
    while(s1 && !s1.isaPalindrome()){
        s1= prompt("enter a word or phrase","");
    }
    if(!s1) s1='Able was I, ere I saw Elba';
    alert(s1 +' is a palindrome');
    </script>
    Last edited by mrhoo; 03-10-2010 at 11:24 PM.

  11. #11
    Join Date
    Jul 2011
    Posts
    2

    Simple Palindrome

    I recently came across http://rindovincent.blogspot.com/p/javascript.html where there was a simple program to generate palindrome. I hope it will be helpful for all beginners like me. I am pasting the same program here with permission.
    Code:
    <html>
    <body>
    <script type="text/javascript">
    function palinChecker()
    {
     var string = document.palindrome.input.value;
     document.palindrome.palindrometext.value = reverseString(string);
    
     if (isPalindrome(string))
     {
       alert("This word is a palindrome.");
     }
     else
     {
       alert("This word is not a palindrome.");
     }
    }
    
    
    function isPalindrome (inputString)
    {
     var reversedString = reverseString(inputString);
     return (reversedString==reverseString(reversedString));
    }
    
    
    function reverseString(stringToReverse)
    {
     stringToReverse = stringToReverse.toUpperCase();
     var reversedString="";
     var length= stringToReverse.length-1;
     var ch;
     for (var i=length; i>=0; i--)
     {
       ch = stringToReverse.charAt(i)
       if(ch >='A' && ch <='Z')
       {
         reversedString += ch;
       }
     }
     return reversedString;
    }
    
    </script>
    
    <form name="palindrome">
    <p>Enter phrase: <input type="text" name="input"><br>
    <input type="button" name="check" value="Check if palindrome" onclick="palinChecker();"><br>
    <input type="text" name="palindrometext" value=""></p>
    </form>
    </body>
    </html>

  12. #12
    Join Date
    Dec 2008
    Posts
    488
    I think this exercise was to teach you about taking a problem, developing the logic to find a solution, and then transposing that logic to programming language.

    Just think about what you do with your own brain to check to see if a word is a palindrome or not:

    1. You see the word
    2. You write (or think of) the letters in reverse order, one at a time
    3. You compare the original and the reverse side-by-side to see if they are equal
    4. If they are equal, you say to yourself "This is a palindrome", and if not, you say to yourself "This is not a palindrome.

    So, in the most simple terms possible, how do you apply that to your programming?

    Start with the basic steps and add in the little extras (i.e. start with a given string for development, then once you get it working, add in things like "prompt()" and "alert()", etc. First thing you need to do is to create a word:

    Code:
    var originalStr, reverseStr = "", i;
    originalStr = "This is not a palindrome";
    Next, you need to reverse the order of letters and build a second string to compare to the original:

    Code:
    for (i = originalStr.length - 1; i > -1; i--) {
        reverseStr = reverseStr + originalStr.charAt(i);
    }
    Now that we have our reverse string, we can compare the two:

    Code:
    if (reverseStr.toUpperCase() === originalStr.toUpperCase()) {
        alert('The string: "' + originalStr + '" is a palindrome.');
    } else {
        alert('The string: "' + originalStr + '" is not a palindrome.');
    }
    Obviously, the string "This is not a palindrome" is not a palindrome, so let's put this all together and try a few strings:

    Code:
    var originalStr, reverseStr = "", i;
    
    originalStr = "Satanoscillatemymetallicsonatas";
    
    for (i = originalStr.length - 1; i > -1; i--) {
        reverseStr = reverseStr + originalStr.charAt(i);
    }
    
    if (reverseStr.toUpperCase() === originalStr.toUpperCase()) {
        alert('The string: "' + originalStr + '" is a palindrome.');
    } else {
        alert('The string: "' + originalStr + '" is not a palindrome.');
    }
    Now that we've tried a few strings, let's get some input from the user:

    Code:
    var originalStr = prompt("Enter a word or phrase to test whether it is a palindrome:"), reverseStr = "", i;
    
    for (i = originalStr.length - 1; i > -1; i--) {
        reverseStr = reverseStr + originalStr.charAt(i);
    }
    
    if (reverseStr.toUpperCase() === originalStr.toUpperCase()) {
        alert('The string: "' + originalStr + '" is a palindrome.');
    } else {
        alert('The string: "' + originalStr + '" is not a palindrome.');
    }
    That's it. Now you can add in whatever HTML you want, change the way input is gathered, add some styling, etc.
    Last edited by jamesbcox1980; 07-13-2011 at 03:53 PM.

  13. #13
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    why does everyone try to make it overly-complex?
    good god; conditionals, needless loops everywhere, arrays, old string methods, variables, when does the madness end?

    this is javascript; you only need one or two lines for simple things like this:


    Code:
    function isPal(str){
      str=str.toLowerCase().replace(/\s/g,"");
      return   str==str.split("").reverse().join("");
    }
    
    alert(
     isPal("A man A plan A canal Panama")
    )
    Last edited by rnd me; 07-13-2011 at 06:26 PM.

  14. #14
    Join Date
    Dec 2008
    Posts
    488
    Quote Originally Posted by rnd me View Post
    why does everyone try to make it overly-complex?
    good god; conditionals, needless loops everywhere, arrays, old string methods, variables, when does the madness end?

    this is javascript; you only need one or two lines for simple things like this:


    Code:
    function isPal(str){
      str=str.toLowerCase().replace(/\s/g,"");
      return   str==str.split("").reverse().join("");
    }
    
    alert(
     isPal("A man A plan A canal Panama")
    )
    Because the OP's lesson wanted him to use a For-loop.

  15. #15
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441

    Exclamation

    Quote Originally Posted by jamesbcox1980 View Post
    Because the OP's lesson wanted him to use a For-loop.
    Maybe, but the OP asked the question in March of 2010!!!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles