1-8 Useful String Methods - Learn Web Development - MDN
1-8 Useful String Methods - Learn Web Development - MDN
Strings as objects
Most things are objects in JavaScript. When you create a string, for example by using
const string = "This is my string";
your variable becomes a string object instance, and as a result has a large number of
properties and methods available to it. You can see this if you go to the String object
page and look down the list on the side of the page!
Now, before your brain starts melting, don't worry! You really don't need to know about
most of these early on in your learning journey. But there are a few that you'll potentially
use quite often that we'll look at here.
Let's enter some examples into the browser developer console.
This should return the number 7, because "mozilla" is 7 characters long. This is useful for
many reasons; for example, you might want to find the lengths of a series of names so you
can display them in order of length, or let a user know that a username they have entered
into a form field is too long if it is over a certain length.
The length of the string "mozilla" is 7, but because the count starts at 0, the last
character's position is 6; using length-1 gets us the last character.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 2/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
if (browserType.includes("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
Often you'll want to know if a string starts or ends with a particular substring. This is a
common enough need that there are two special methods for this: startsWith() and
endsWith() :
if (browserType.startsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
if (browserType.endsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 3/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
Starting at 0 , if you count the number of characters (including the whitespace) from the
beginning of the string, the first occurrence of the substring "developers" is at index 20 .
console.log(tagline.indexOf("x")); // -1
This, on the other hand, returns -1 because the character x is not present in the string.
So now that you know how to find the first occurrence of a substring, how do you go
about finding subsequent occurrences? You can do that by passing in a value that's
greater than the index of the previous occurrence as the second parameter to the
method.
const firstOccurrence = tagline.indexOf("developers");
const secondOccurrence = tagline.indexOf("developers", firstOccurrence + 1);
console.log(firstOccurrence); // 20
console.log(secondOccurrence); // 35
Here we're telling the method to search for the substring "developers" starting at index 21
( firstOccurrence + 1 ), and it returns the index 35 .
The character at index 1 is "o" , and the character at index 4 is "l" . So we extract all
characters starting at "o" and ending just before "l" , giving us "ozi" .
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 4/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
If you know that you want to extract all of the remaining characters in a string after a
certain character, you don't have to include the second parameter. Instead, you only need
to include the character position from where you want to extract the remaining characters
in a string. Try the following:
browserType.slice(2); // "zilla"
This returns "zilla" — this is because the character position of 2 is the letter "z" , and
because you didn't include a second parameter, the substring that was returned was all of
the remaining characters in the string.
Note: slice() has other options too; study the slice() page to see what else
you can find out.
Changing case
The string methods toLowerCase() and toUpperCase() take a string and convert all the
characters to lower- or uppercase, respectively. This can be useful for example if you want
to normalize all user-entered data before storing it in a database.
Let's try entering the following lines to see what happens:
const radData = "My NaMe Is MuD";
console.log(radData.toLowerCase());
console.log(radData.toUpperCase());
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 5/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
console.log(updated); // "vanilla"
console.log(browserType); // "mozilla"
Note that replace() , like many string methods, doesn't change the string it was called on,
but returns a new string. If you want to update the original browserType variable, you would
have to do something like this:
let browserType = "mozilla";
browserType = browserType.replace("moz", "van");
console.log(browserType); // "vanilla"
Also note that we now have to declare browserType using let , not const , because we are
reassigning it.
Be aware that replace() in this form only changes the first occurrence of the substring. If
you want to change all occurrences, you can use replaceAll() :
let quote = "To be or not to be";
quote = quote.replaceAll("be", "code");
Live output
Happy Birthday!
Merry Christmas my love
A happy Christmas to all the family
You're all I want for Christmas
Get well soon
Editable code
Press Esc to move focus away from the code area (Tab inserts a tab character).
Fixing capitalization
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 7/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
In this exercise, we have the names of cities in the United Kingdom, but the capitalization
is all messed up. We want you to change them so that they are all lowercase, except for a
capital first letter. A good way to do this is to:
1. Convert the whole of the string contained in the city variable to lowercase and store
it in a new variable.
2. Grab the first letter of the string in this new variable and store it in another variable.
3. Using this latest variable as a substring, replace the first letter of the lowercase string
with the first letter of the lowercase string changed to upper case. Store the result of
this replacement procedure in another new variable.
4. Change the value of the result variable to equal to the final result, not the city .
Note: A hint — the parameters of the string methods don't have to be string
literals; they can also be variables, or even variables with a method being invoked
on them.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 8/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
Live output
lonDon
ManCHESTer
BiRmiNGHAM
liVERpoOL
Editable code
Press Esc to move focus away from the code area (Tab inserts a tab character).
We want to extract the station code and name, and put them together in a string with the
following structure:
MAN: Manchester Piccadilly
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 9/11
12/06/2023, 16:21 Useful string methods - Learn web development | MDN
Live output
MAN675847583748sjt567654;Manchester Piccadilly
GNF576746573fhdg4737dh4;Greenfield
LIV5hg65hd737456236dch46dg4;Liverpool Lime Street
SYB4f65hf75f736463;Stalybridge
HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield
Editable code
Press Esc to move focus away from the code area (Tab inserts a tab character).
'GNF576746573fhdg4737dh4;Greenfield',
'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
You've reached the end of this article, but can you remember the most important
information? You can find some further tests to verify that you've retained this information
before you move on — see Test your skills: Strings.
Conclusion
You can't escape the fact that being able to handle words and sentences in programming
is very important — particularly in JavaScript, as websites are all about communicating
with people. This article has given you the basics that you need to know about
manipulating strings for now. This should serve you well as you go into more complex
topics in the future. Next, we're going to look at the last major type of data we need to
focus on in the short term — arrays.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods 11/11