As we have learned, strings are immutable. Therefore, string methods will not change the value of a string itself, but instead will return a new string that is the result of the given operation.
We saw this behavior in the
let nonprofit = "LaunchCode"; console.log(nonprofit.toLowerCase()); console.log(nonprofit);
nonprofit.toLowerCase() evaluated to
"launchcode", the value of
nonprofit was left unchanged. This will be case for each of the string methods.
Common String Methods
Here we present the most commonly-used string methods. You can find documentation for other string methods at:
|indexOf||Returns the index of the first occurrence of the substring in the string, and returns -1 if the substring is not found.|
|toLowerCase||Returns a copy of the given string, with all uppercase letters converted to lowercase.|
|toUpperCase||Returns a copy of the given string, with all lowercase letters converted to uppercase.|
|trim||Returns a copy of the given string with the leading and trailing whitespace removed.|
|replace||Returns a copy of |
|slice||Returns the substring consisting of characters from index |
String methods can be combined in a process called method chaining. Given
Check Your Understanding
Follow the links in the table above for the
trim methods. Review the content and then answer the following questions.
What is printed by the following code?
What is the value of the string printed by the following program?
let org = " The LaunchCode Foundation "; let trimmed = org.trim(); console.log(trimmed);
" The LaunchCode Foundation "
"The LaunchCode Foundation"
" The LaunchCode Foundation"