Strings are used in JavaScript for text. You can enclose strings in either single or double quotes.
var myString = "Hello AHS!";
Because we sometimes need to use the character ' or " within a string, we use the \ as a special indicator:
var myString = 'Karl\'s classroom.';
Just as in Python, there are various "methods" you can use with strings.
var myString ="Hello AHS!";
var stringLength = myString.length;
stringLength would equal 10 in this case.
We can use indexOf() to find the position of text within a string:
var myString ="Hello AHS!";
var position = myString.indexOf("o");
would return 4 (remember, computers start counting with 0 - so do indexes).
lastIndexOf() returns the last occurrance.
search() is very similar to indexOf(), but has more flexibility in the search values. We'll talk more about this when we talk about regular expressions.
slice(), substring(), and substr() are all ways to extract (pull out) parts of a string.
var myString ="Hello AHS!";
var part = myString.slice(6,10);
part would equal "AHS!".
If you use negative parameters, it counts from the end of the string. If you just use one parameter, it slices out the rest of the string. Substring is just like slice except you can't use negatives.
var myString ="Hello AHS!";
var part = myString.substring(6, 10);
substr is like slice and substring except you specify the length of how many characters you want to extract.
var myString ="Hello AHS!";
var part = myString.substr(6, 4);
replace(), well, replaces part of a string:
var myString ="Hello AHS!";
var part = myString.replace("Hello", "Goodbye");
toUpperCase() and toLowerCase() do what you would expect.
concat() joins together two or more strings.
var myString1 ="Hello";
var myString2 ="Dolly";
var myString3 = myString1.concat(" ", myString2);
charAt() returns the character at a given index in the string.
We can convert a string to an array using split() (more on this later).