Strings
JavaScript Strings
The String is one of the most used objects in JavaScript, which is why it is so important to know its properties and methods. To clear up some confusion, you already know this object as a string variable. As explained in the previous tutorial, this variable was created by a string()
function. So, this variable is actually an object with properties and methods.
The string is a pretty large class because developers want to do so many different things with strings. The idea of a string in itself is very complicated. You might want to know how many “e” characters are in it, but you might also want to know the total number of characters in the string. These are just two common reasons why we have properties. JavaScript provides us with a wealth of properties to get what we need from our strings.
Common String Properties
- constructor – tells us the function that created the String object’s prototype
- length – returns the total number of characters in a string
Example
var example = "Meerkat";
document.write(example.constructor);
Result
function String() [native code]
Common String Methods
A string is a very changeable variable, which means you need to be careful when using string methods. Many of the string methods will manipulate the initial value of the string, which cannot be recovered. Methods are easily distinguished by the fact they have ()
following them.
- charAt() – returns a character using its index
- indexOf() – returns the index of the first instance of a specified value
- lastIndexOf() – returns the index of the last instance of a specified value
- match() – finds all matches in the string of a specified value
- replace() – finds and replaces all matches in the string with a new substring
- search() – looks for a match in the string and returns the substring's index
- slice() – extracts and returns part of the string
- split() – splits the string into an array of substrings
- substr() – extracts characters starting at a specified position and ending after a certain length
- substring() – extracts characters starting between two specified positions
- toLowerCase() – converts all letters in a string to lowercase
- toUpperCase() – converts all letters in a string to uppercase
Example
var example = "Meerkat";
document.write(example.charAt(0));
Result
M
Combining Strings
var string1 = "You are awesome, ";
var string2 = "and you know it.";
var combined = string1 + string2;
document.write(combined);
Result
You are awesome, and you know it.