Strings in JavaScript
by danielkwood
HTML
<html>
<head>
<title>Strings</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
JavaScript
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[2]);
// 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[4]);