Most things are objects in JavaScript. When you create a string, for example by using
let 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 is easy — you simply use the length
property. Try entering the following lines:
let browserType = 'mozilla'; browserType.length;
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.
On a related note, you can return any character inside a string by using square bracket notation — this means you include square brackets ([]
) on the end of your variable name. Inside the square brackets you include the number of the character you want to return, so for example to retrieve the first letter you’d do this:
browserType[0];
Remember: computers count from 0, not 1! You could use this to, for example, find the first letter of a series of strings and order them alphabetically.
To retrieve the last character of any string, we could use the following line, combining this technique with the length
property we looked at above:
browserType[browserType.length-1];
The length of “mozilla” is 7, but because the count starts at 0, the character position is 6; using length-1
gets us the last character.
Sometimes you’ll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). This can be done using the indexOf()
method, which takes a single parameter — the substring you want to search for.
If the substring is found inside the main string, it returns a number representing the index position of the substring — which character number of the main string the substring starts at. If the substring is not found inside the main string, it returns a value of -1
.
browserType.indexOf('zilla');
This gives us a result of 2, because the substring “zilla” starts at position 2 (0, 1, 2 — so 3 characters in) inside “mozilla”. Such code could be used to filter strings. For example, we may have a list of web addresses and only want to print out the ones that contain “mozilla”.
browserType.indexOf('vanilla');
This should give you a result of -1
— this is returned when the substring, in this case ‘vanilla’, is not found in the main string.
You could use this to find all instances of strings that don’t contain the substring ‘mozilla’ (or do, if you use the negation operator, !==
):
if(browserType.indexOf('mozilla') === -1) { // do stuff with the string if the 'mozilla' // substring is NOT contained within it } if(browserType.indexOf('mozilla') !== -1) { // do stuff with the string if the 'mozilla' // substring IS contained within it }
slice()
can be used to extract it. Try the following:
browserType.slice(0,3);
This returns “moz” — the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position. In this example, since the starting index is 0, the second parameter is equal to the length of the string being returned.
browserType.slice(2);
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: The second parameter of slice()
is optional: if you don’t include it, the slice ends at the end of the original string. There are other options too; study the slice()
page to see what else you can find out.
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:
let radData = 'My NaMe Is MuD'; radData.toLowerCase(); radData.toUpperCase();
You can replace one substring inside a string with another substring using the replace()
method. This works very simply at a basic level, although there are some advanced things you can do with it that we won’t go into yet.
It takes two parameters — the string you want to replace, and the string you want to replace it with. Try this example:
browserType.replace('moz','van');
This returns “vanilla” in the console. But if you check the value of browserType
, it is still “mozilla”. To actually update the value of the browserType
variable in a real program, you’d have to set the variable value to be the result of the operation; it doesn’t just update the substring value automatically. So you’d have to actually write this: browserType = browserType.replace('moz','van');
In this section we’ll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don’t need to understand arrays or loops right now — these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.
Each example comes with a “Reset” button, which you can use to reset the code if you make a mistake and can’t get it working again, and a “Show solution” button you can press to see a potential answer if you get really stuck.
In the first exercise we’ll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the if( ... )
structure, to test each string and only print it in the list if it is a Christmas message.
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 lower case, except for a capital first letter. A good way to do this is to:
input
variable to lower case and store it in a new variable.result
variable to equal to the final result, not the input
.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.
In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:
MAN675847583748sjt567654;Manchester Piccadilly
We want to extract the station code and name, and put them together in a string with the following structure:
MAN: Manchester Piccadilly
We’d recommend doing it like this:
result
variable to equal to the final string, not the input
.In our first strings task, we start off small. You already have half of a famous quote inside a variable called quoteStart
; we would like you to:
quoteEnd
.finalQuote
.You’ll find that you get an error at this point. Can you fix the problem with quoteStart
, so that the full quote displays correctly?
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
In this task you are provided with two variables, quote
and substring
, which contain two strings. We would like you to:
quoteLength
.substring
appears in quote
, and store that value in a variable called index
.revisedQuote
.Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
In the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! We want you to fix and update it, like so:
fixedQuote
.fixedQuote
, replace “green eggs and ham” with another food that you really don’t like.finalQuote
.Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
In the final string task, we have given you the name of a theorem, two numeric values, and an incomplete string (the bits that need adding are marked with asterisks (*
)). We want you to change the value of the string as follows:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
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.