This video tutorial explains some different tasks you can perform with strings including:
- how to concatenate (join) strings together
- how to convert from integer to string
- ho to change text to uppercase or lowercase letters
- how to extract characters or portions of a string
- indexing (accessing individual characters in a string)
- how to split a string into different parts
Watch the videos below and scroll down for the sample code.
The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.
These string methods might not seem that useful at the moment, but they will come in handy later. For example, imagine you are creating an app and users need to create a password for logging in. You might want to know the length of their password (stored as a string) to check it meets the minimum length for security requirements, or you might want to make sure a user’s phone number is not too long, or you might want to format someone’s name like changing the first letter of their first name and surname to uppercase.
Here is the HTML code:
<html> <head> <title>Strings</title> <script src="script.js"></script> </head> <body> </body> </html>
var firstname = "Joe"; var lastname = "Bloggs"; // Concatenation (joining strings together) var fullname = firstname + " " + lastname; console.log(fullname); // Find the length (number of characters) of a string var namelength = fullname.length; console.log(namelength); var phone = 401123456; var countrycode = 61; // Convert integers or floats to strings var phonestring = countrycode.toString() + phone.toString(); console.log(phonestring); // Return individual characters in a string console.log(fullname); // another method... console.log(fullname.charAt(2)); // Return position (index) of a character in a string console.log(fullname.indexOf('e')); // Convert string to lowercase console.log(fullname.toLowerCase()); // Convert string to uppercase console.log(fullname.toUpperCase()); var sentence = "The quick brown fox jumps over the lazy dog"; // Substring method extracts part of a string // This will extract characters from index 5 up until index 12 console.log(sentence.substring(5,12)); // Substr method extracts part of a string, but differently // This will extract 3 characters from index 6 console.log(sentence.substr(6,3)); // This will split a string wherever a space occurs // Each word will be placed into an array (list) of strings var words = sentence.split(" "); // This will display the fifth string (word) in the array console.log(words);
Next tutorial: Events