Login | Register | FAQ
Anonymous


Lesson 10: JavaScript Objects - Strings

By Maria Antonietta Perna

In the previous lesson you were introduced to the concept of Object Oriented Programming (OOP). You're now familiar with the use of objects and their properties and methods in JavaScript programming.

Starting from this lesson and for the next 3 lessons, we will be getting up close and personal with some of the most common properties and methods of widely used JavaScript objects: String, Date, Math, and Array. However, because JavaScript as a programming language is mostly made of objects, you will keep learning to use more objects and related properties and methods throughout the rest of this tutorial.

In this lesson you will learn how to use the following properties and methods of the string object:

  • length property;
  • toLowerCase()/toUpperCase();
  • match();
  • replace();
  • indexOf().

In the process, you will also practice putting your JavaScript code into an external file.

The String object

You've had plenty of practice with the string object through this tutorial. In fact, the JavaScript interpreter reads any piece of text enclosed in quotes ' ' (or double quotes " ") as an instance of the string object. This puts the magic of all the properties and methods belonging to the string object in our hands.

The beauty of Object Oriented Programming is that we can use all that JavaScript goodness to achieve our script's goals without needing to have any clue whatsoever of the inner workings of those properties and methods. All we need to know is what a property or method can do for us, not how it does it.

For example, if we need to know the length of a piece of text, just using pieceOfText.length will achieve this. This is accomplished without us knowing anything of the programming virtuosity responsible for the power of the length property of the string object.

Let's have a taste of such power.

How to use length

The length property of the string object contains the number of characters (including spaces) in the text value of a string.

Here's a basic code snippet to demonstrate its use:

		
	  //create and initialize a string variable
		
	  var myString = "Hello JavaScript"
		
	  //apply the length property to the string
		
	  document.write(myString.length);
		
	  //JavaScript will print 16:
		
	  //spaces are included in the count
		
	  //If the string is empty length returns 0
		
	  

Try out for yourself: insert the code above between enclosing <script> tags and have fun experimenting with it.

How to use toUpperCase()

The toUpperCase() method of the string object turns the text value of a string into, well ... uppercase letters. Its companion toLowerCase() does the opposite: it turns the text value of a string into lowercase letters.

Here's a basic code snippet to demonstrate its use:

		
	  //create and initialize a string variable
		
	  var myString = "Hello JavaScript"
		
	  //apply the toUpperCase() method to the string
		
	  document.write(myString.toUpperCase());
		
	  //JavaScript will print HELLO JAVASCRIPT
		
	  //Try using myString.toLowerCase() on your own
		
	  

Have a try: insert the code above between enclosing <script> tags and switch uppercase into lowercase.

How to use match()

The match() method of the string object is used to search for a specific value inside a string.

Here's a basic code snippet to demonstrate its use:

		
	  //create and initialize a string variable
		
	  var myString = "Hello JavaScript"
		
	  //apply the match() method to the string.
		
	  //match(stringToMatch) takes the value to search for as argument
		
	  document.write(myString.match("JavaScript"));
		
	  //JavaScript will print JavaScript
		
	  //If no match is found the method returns null
		
	  

Experiment on your own: insert the code above between enclosing <script> tags and try matching different string values.

How to use replace()

The replace() method of the string object is used to replace a value for another value inside a string.

Here's a basic code snippet to demonstrate its use:

		
	  //create and initialize a string variable
		
	  var myString = "Hello JavaScript"
		
	  //apply the replace() method to the string.
		
	  //replace() takes 2 arguments and returns the new string value:
		
	  //replace(valueToReplace, newValue)
		
	  document.write(myString.replace("JavaScript", "World"));
		
	  //JavaScript will print Hello World
		
	  

Have a go: insert the code above between enclosing <script> tags and try replacing different string values.

How to use indexOf()

The indexOf() method of the string object is used to know the position of the first found occurrence of a value inside a string.

Here's a basic code snippet to demonstrate its use:

		
	  //create and initialize a string variable
		
	  var myString = "Hello JavaScript"
		
	  //apply the indexOf() method to the string.
		
	  //indexOf() takes in the value to look for in the string as argument
		
	  //and returns the position number (index)
		
	  //indexOf(valueToFind)
		
	  document.write(myString.indexOf("Java"));
		
	  //JavaScript will print 6
		
	  //indexOf() includes spaces and starts counting at 0 
		
	  //if no value is found the method returns -1
		
	  

Have a go on your own: insert the code above between enclosing <script> tags and print the index position of different letters inside the string.

Try out: guessing game

You're going to build a simple guessing game application using all the new knowledge you've acquired in this lesson. Your application is expected to check a name entered by the user and respond accordingly:

Your JavaScript code will be placed in its own external file and referenced from the HTML document. Separation of concerns, that is, separation between structure (HTML mark-up), appearance (CSS), and behavior (JavaScript), reflects contemporary best practices in web design.

Let's start with the HTML document. This is a simple web page with a textbox, a button, and a div where the JavaScript result will be displayed:

		
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>Lesson 10: JavaScript Objects - Strings</title>
	  <script type="text/javascript" src="lesson10.js"></script>
	  </head>
	  <body>
	  <h1>Lesson 10: JavaScript Objects - Strings</h1>
		
	  <h2>What's the name of the wizard boy in J.K. Rowling's novels?</h2>
		
	  <p>Your answer: <input type="text" id="txtName" /></p>
	  <p><input type="button" value="Submit your answer" id="btnAnswer" />
		
	  <p id="message"></p>
		
	  </body>
	  </html>
		
	  

Pay attention to the enclosing <head> tags. These contain a reference to an external JavaScript file named lesson10.js located in the same directory as the HTML file (you're free to place the JavaScript file in its own directory, if you prefer. However, make sure this is reflected in the src value of your <script> tag in the HTML document).

Also, take note of the fact that the elements that are going to play a role in our script all have an id attribute. This gives JavaScript a hook on those elements and the data they will eventually contain.

Now open the JavaScript file lesson10.js and type the following code:

		
	  //This is the function that initializes our program
		
	  function init()
		
	  {
		
	  //Store a reference to the HTML button element in a variable:
		
	  //use the id of the HTML button element to do this
		
	  var myButton = document.getElementById("btnAnswer");
		
		
	  //use the onclick event of the button
		
	  //and assign the value of the getAnswer() function to it.
		
	  //This function performs the main job in your application
	  
	  //and runs after the user clicks the button on the page.
		
	  //Take note: getAnswer is assigned without brackets.
		
	  //This is so because otherwise getAnswer() would be called
		
		//as soon as the page loads (and we don't want that).
		
	  myButton.onclick = getAnswer;
		
		
	  //the init function ends here
		
	  }
		
		
	  //Assign the init() function to the onload event:
		
	  //this event fires when the HTML page is loaded in the browser.
		
	  //Take note: init is assigned without brackets
		
	  onload = init;
		
		
	  //Now write the getAnswer() function
		
	  function getAnswer()
		
	  {
		
	  //Create all the vars you need to manipulate your data:
		
	  //secretName stores the correct answer the user is expected to guess:
		
	  var secretName = "Harry Potter";
		
		
	  //Turn the value of secretName into lower case:
		
	  //you do this because you're going to compare this value
		
	  //to the value entered by the user of your application.
		
	  //Given that users might type the answer either in upper or lower case,
		
	  //reducing the relevant text values to the same casing automatically
		
	  //ensures that only the content and not also the letter case plays a role in the comparison.
		
	  var secretNameLower = secretName.toLowerCase();
		
		
	  //Get the value the user types into the textbox
		
	  var myTextBox = document.getElementById("txtName");
		
	  var name = myTextBox.value;
		
		
	  //Also turn the value entered by the user to lower case
		
	  var nameLower = name.toLowerCase();
		
		
	  //Get a reference to the HTML paragraph that will display your result
		
	  //after the script has run by storing its id value in a var
		
	  var message = document.getElementById("message");
		
		
	  //These are the test cases your application needs to evaluate
		
	  //and respond to: if the user clicks the button but did not
		
	  //enter any value in the textbox:
		
	  if(nameLower.length <= 0)
		
	  {
		
	  alert("I didn't quite catch your answer.  Please enter an answer");
		
	  }
		
		
	  //If the user gets right the first half but not the latter half of the name:
		
	  //Take note of the use of the logical operator && 
		
	  //(go back to lesson 5 if you need to revise logical operators)
		
	  else if(nameLower.indexOf("harry") == 0 && nameLower.indexOf("potter") == -1)
		
	  {
		
	  alert("Almost there: think again");
		
	  }
		
		
	  //If the secret name and the name entered by the user match:
		
	  else if(nameLower.match(secretNameLower))
		
	  {
		
	  alert("You got it!");
		
	  message.innerHTML = "Congratulations, you win!";
		
	  }
		
		
	  //Default case - if the user types in the wrong answer:
		
	  else
		
	  {
		
	  alert("Wrong!");
		
	  message.innerHTML = "Sorry.  The correct answer is: ";
		
	  message.innerHTML += name.replace(name, "Harry Potter");
		
	  }
		
		
	  //the getAnswer() function ends here
		
	  }
		
	  

Save all your files and run the HTML page in the browser. You should see something similar to the example page indicated in the link above.

If you click the button without entering any value in the textbox, an alert will pop up inviting you to enter an answer.

If you get right the first half ("Harry") - indexOf() returns 0 ("Harry" is at position 0, which is the start of the index) - but not the latter half ("Potter") - indexOf() returns -1 (it finds no corresponding value inside the string), you get an alert letting you know that your answer is almost right.

If you enter the correct answer, well you'll get a prize.

Finally, if your answer is totally wrong, your application will say so and give you the correct answer.

The above code sample employs all the JavaScript tools you learned in this lesson and most of those you encountered in previous lessons. Experiment with it as much as you can. If you have doubts, leave a message in our JavaScript forum.

The really new stuff in the guessing game application is the way JavaScript functions work from an external file. This is the technique I'm going to use for our Try out exercises in most of the remaining part of this tutorial - at least until jQuery makes its appearance. This means that you'll be getting plenty of practice with it.

Summary

In this lesson you started to have a taste of the power of objects. You also started to use an external JavaScript file for your Try out exercise, thereby conforming to best practice in contemporary web design techniques. Now have a break and get yourself ready for the next topic: the Date object.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 9: A Gentle Introduction to Objects

Lesson 11: JavaScript Objects: Date Object >>