#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Manipulating A String


    I'm in the process of learning javascript, and for an assignment I have to write a script that capitalizes the first letter in each word of a string using the split method to break down each word, another split method in a loop to isolate and capitalize each first letter element. I've written what I thought would work, however, for some reason it's not returning my expected result. I've tried to comment each process in my logic to help me understand. Can someone point out where I may be heading in the wrong direction?
    thanks

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    	<title>Manipulating Strings</title>
    
    
    	<script type="text/javascript">
    
    	/* <![CDATA[ */
    
    function convertTitleCase(string1){
    	
    	var string1;
    	
    	//break the variable string1 each word into the array string1Array
    	var string1Array = string1.split(" ");
    		
    	
    	//break each word/element from String1 Array into letters into the array singleLetterArray
    	var singleLetterArray = string1Array.split(" ");
    	
    	
    	//using a for loop, capitalize the first element in each array
    		for (var i=0; i <singleLetterArray.length; ++i){
    		singleLetterArray[0] = singleLetterArray[0].toUpperCase();
    		
    		//join the letters to create the word & assign to appropriate element
    		var combinedWord = singleLetterArray.join(" ");
    		string1Array[i] = combinedWord;
    		}
    	//join the words to create the string
    	string1 = string1Array.join(" ");	
    	
    	//write the string to the textbox
    	document.forms.form1.string1.value = string1;
    	
    }
    
    
    
    		
    /* ]]> */
    </script>
    
    </head>
    
    
    
    <body>
    
    	<form action"" method="post" name="form1">
    
    <p> Enter your text string.</p>
    <p><input type="text" name="string1" value="" 
    /></p>
    
    <input type="button" onclick="convertTitleCase(document.forms.form1.string1.value)" value="Convert to Title Case" />
    </form>
    
    </body>
    </html>
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2006
    Location
    England
    Posts
    397
    Rep Power
    76
    Originally Posted by KirbyLastName
    I have to write a script that capitalizes the first letter in each word of a string using the split method to break down each word, another split method in a loop to isolate and capitalize each first letter element.
    That is unnecessarily complicated but if it's what's required...

    The best help I can give is to tell you to learn to use the error console, and to ask your teacher (if you have one) why you weren't taught so to do.
    FireFox has the best error console and it is located under 'Tools'.


    No it's not 'awesome' - it's just code.
  4. #3
  5. Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Aug 2005
    Location
    Bucharest ROMANIA
    Posts
    2,524
    Rep Power
    609
    Not a good approach. You don't need to split, nor to break down each word. A word is always preceded by a space (except the first word, which is to be treated as an exception), so all you have to do is to circle trough the string and capitalize each first letter after a space:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <script type="text/javascript">
    function capitalize(){
    var div=document.getElementById('mydiv');
    var txt=div.innerHTML;
    newTxt='';
    for(var i=0;i<txt.length;i++){
    if(i==0){newTxt+=txt[i].toUpperCase()}
    else{newTxt+=txt[i]};
    if(txt.charAt(i)==' '){newTxt+=txt[i+1].toUpperCase();i++}
    }
    div.innerHTML=newTxt;
    }
    </script>
    </head>
    <body>
    <div id="mydiv">lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus et ullamcorper malesuada, enim turpis pharetra nunc, nec vehicula leo dolor ac ipsum. Donec consectetur interdum eros, eget blandit justo ultrices non. Pellentesque in augue nec nulla hendrerit fringilla. Donec ante diam, sagittis a aliquet sit amet, malesuada in dolor. Donec dapibus magna nec tellus auctor condimentum. In auctor nunc ut mi ultricies auctor. Nullam tellus nunc, aliquet nec placerat ut, placerat vitae velit. Nullam nec hendrerit neque. Quisque id ante at erat commodo pretium sed et purus.</div>
    <br>
    <br>
    <a href="#" onclick="capitalize()">capitalize the text</a>
    </body>
    </html>
    But tell your teacher that usually a string is handled easier on using Regular Expressions:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <script type="text/javascript">
    function capitalize(){
    var div=document.getElementById('mydiv')
    var txt=div.innerHTML;
    div.innerHTML=cnvrt2Upper(txt);
    }
    function cnvrt2Upper(str) {
            return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
            function cnvrt() {
                return arguments[0].toUpperCase();
            }
        }
    </script>
    </head>
    <body>
    <div id="mydiv">lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus et ullamcorper malesuada, enim turpis pharetra nunc, nec vehicula leo dolor ac ipsum. Donec consectetur interdum eros, eget blandit justo ultrices non. Pellentesque in augue nec nulla hendrerit fringilla. Donec ante diam, sagittis a aliquet sit amet, malesuada in dolor. Donec dapibus magna nec tellus auctor condimentum. In auctor nunc ut mi ultricies auctor. Nullam tellus nunc, aliquet nec placerat ut, placerat vitae velit. Nullam nec hendrerit neque. Quisque id ante at erat commodo pretium sed et purus.</div>
    <br>
    <br>
    <a href="#" onclick="capitalize()">capitalize the text</a>
    </body>
    </html>
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2006
    Location
    England
    Posts
    397
    Rep Power
    76
    Originally Posted by KorRedDevil
    But tell your teacher that usually a string is handled easier on using Regular Expressions
    I agree:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Capitalise Text</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
    <script type="text/javascript">
    
    function capitalise( elem )
    { 
     elem.value = elem.value.replace( /\b./g, function( a ){ return a.toUpperCase(); } );
    }
    
    </script>
    </head>
    <body>
    <p>
     <textarea id='ta1' rows='10' cols='40'>loremipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus et ullamcorper malesuada, enim turpis pharetra nunc, nec vehicula leo dolor ac ipsum. Donec consectetur interdum eros, eget blandit justo ultrices non. Pellentesque in augue nec nulla hendrerit fringilla. Donec ante diam, sagittis a aliquet sit amet, malesuada in dolor. Donec dapibus magna nec tellus auctor condimentum. In auctor nunc ut mi ultricies auctor. Nullam tellus nunc, aliquet nec placerat ut, placerat vitae velit. Nullam nec hendrerit neque. Quisque id ante at erat commodo pretium sed et purus.
     </textarea>
     <br>
     <br>
     <a href="#" onclick="capitalise( document.getElementById( 'ta1' ) );return false;">Capitalise</a>
    </body>
    </html>


    No it's not 'awesome' - it's just code.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0
    Originally Posted by Arty Effem
    I agree:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Capitalise Text</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
    <script type="text/javascript">
    
    function capitalise( elem )
    { 
     elem.value = elem.value.replace( /\b./g, function( a ){ return a.toUpperCase(); } );
    }
    
    </script>
    </head>
    <body>
    <p>
     <textarea id='ta1' rows='10' cols='40'>loremipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus et ullamcorper malesuada, enim turpis pharetra nunc, nec vehicula leo dolor ac ipsum. Donec consectetur interdum eros, eget blandit justo ultrices non. Pellentesque in augue nec nulla hendrerit fringilla. Donec ante diam, sagittis a aliquet sit amet, malesuada in dolor. Donec dapibus magna nec tellus auctor condimentum. In auctor nunc ut mi ultricies auctor. Nullam tellus nunc, aliquet nec placerat ut, placerat vitae velit. Nullam nec hendrerit neque. Quisque id ante at erat commodo pretium sed et purus.
     </textarea>
     <br>
     <br>
     <a href="#" onclick="capitalise( document.getElementById( 'ta1' ) );return false;">Capitalise</a>
    </body>
    </html>
    The assignment was from a textbook. It was a lesson on not only string manipulation but also array manipulation. There are no doubt better and more streamlined ways to accomplish this. As I said I'm in the process of learning this. It's becoming a reoccurring theme on this site to critique the "why" question as opposed to offering assistance to the "how" question. Out of 2 replies no suggestions were given. Please consider this in the future when newbs are asking for help. We aren't looking for preachers, we are looking for guidance from those of you with experience.

    Comments on this post

    • Joseph Taylor agrees
    • KorRedDevil disagrees : If you don't like an advice, feel free not to follow it. But don't offend anyone who tries to help you
  10. #6
  11. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2006
    Location
    England
    Posts
    397
    Rep Power
    76
    Originally Posted by KirbyLastName
    We aren't looking for preachers, we are looking for guidance from those of you with experience.
    I can only stand-by the guidance I gave you initially. If you read the content of the error console you'll be immediately aware of the syntactical errors you're making. Having fixed them you can go on to work on your own algorithm.


    No it's not 'awesome' - it's just code.
  12. #7
  13. c0der
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2005
    Location
    Vancouver
    Posts
    664
    Rep Power
    159
    I actually came to this thread a while back with the same sort of response as we've seen (a concise regular expression), but decided against posting it because I realized that I would just be showing off and not really helping you find a solution to your assignment. Arty has a point about that error console thing; the answer did seem to jump out at me from the console, but then again I've been coding JavaScript for a long time.

    A lengthy written explanation would be tiresome to prepare, and it's difficult to get the degree of specificity in a response right. I can be very general, like Arty was, or I can just hand you the answer and be done with it. I've opted to strike a balance through video: I'll give you the exact answer (read: spoilers ahead), but you can't copy/paste it and hopefully you'll gain some insight into my thought process as you watch me navigate the problem.

    So here it is. It's a silent movie (I have roommates which makes narration awkward), and it might be a little hard to read the text. But hey, I tried.

  14. #8
  15. Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Aug 2005
    Location
    Bucharest ROMANIA
    Posts
    2,524
    Rep Power
    609
    Originally Posted by KirbyLastName
    It's becoming a reoccurring theme on this site to critique the "why" question as opposed to offering assistance to the "how" question. Out of 2 replies no suggestions were given. Please consider this in the future when newbs are asking for help. We aren't looking for preachers, we are looking for guidance from those of you with experience.
    Wrong approach again. You wrote quite clearly:
    Originally Posted by KirbyLastName
    Can someone point out where I may be heading in the wrong direction?
    No suggestions were given? have you bothered to read our posts? I told you that your approach was wrong from the very begining, and I gave you two different solutions: one using classical methods, one using Regular Expressions. What do you expect more? Even if your initial approach was your teacher's approach, I don't change my mind: wrong approach.

    I don't care where your assignment came from. It could be a 15 years old textbook, in which case half of what you read there is either deprecated or incomplete.

    And I keep my assertion: string manipulation it is to be done merely using Regular Expression.

    By short: You asked us how to scratch your left eye with your right hand bent behind your head. I was told you that you may do that passing your hand in front of your face, not behind [my first solution: no split() is needed], or, even better you may use, more convenient, your left hand, as being nearer [my second solution, RegExp]. Now you come and tell us that our advice was not what you expected. Is it our fault that what you expected has nothing to do with the programming paradigms?

    If your teacher want's you to use by all means the split() method to capitalize the first letter of a word, then ask him what is wrong? If your question was about how to use the method split(), then obviously that was a bad assignment.

    The final aim for you is to learn JavaScript, not to code something only in a certain way. It is not enough to apply blindly some methods; you should be able to choose the proper method by yourself. Use your intelligence to progress, not the assignments your teacher might have given you.

    Comments on this post

    • Joseph Taylor agrees : For some reason I missed your answer using the loop and split.
    Last edited by KorRedDevil; November 1st, 2010 at 04:19 AM.

IMN logo majestic logo threadwatch logo seochat tools logo