Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1084163 of Handling text — strings in JavaScript

  • Revision slug: Learn/JavaScript/First_steps/Strings
  • Revision title: Handling text — strings in JavaScript
  • Revision id: 1084163
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{draft}}

{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

{{IncludeSubnav("/en-US/Learn")}}

Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common useful things that you really ought to know when learning JavaScript, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective: To gain familiarity with the basics of Maths in JavaScript.

The power of words

Words are very important to humans — they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. {{glossary("HTML")}} provides structure and meaning to our text, {{glossary("CSS")}} allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages, showing the right text labels when needed, sorting terms into the desired order, and so much more.

Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.

Strings — the basics

Strings are dealt with in a similar way to numbers at first glance, but you'll start to see some notable differences when you dig deeper. Let's start by entering some basic lines in a console to familiarise ourselves. We've provided one below (you can also open this console in a separate tab or window, or use the browser developer console if you'd prefer).

{{ EmbedLiveSample('Hidden_code', '100%', 300) }}

Creating a string

To start with, enter the following lines:

var string = 'The revolution will not be televised.';
string;

Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.

If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:

var badString = This is a test;
var badString = 'This is a test;
var badString = This is a test';

These lines don't work because any text string without quotes around it is assumed to be a variable name, property name, reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing ; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.

The following will work if you previously defined the variable string — try it now:

var badString = string;
badString;

badString is now set to have the same value as string.

Single quotes versus double quotes

In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work ok:

var sgl = 'Single quotes.'
var dbl = "Double quotes";
sgl;
dbl;

There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it however, differently quoted code can be confusing, especially if you use the different quotes on the same string! The following will return an error:

var badQuotes = 'What on earth?";

The browser will think the string has not been closed, because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are ok:

var sglDbl = 'Would you eat a "fish supper"?'
var dblSgl = "I'm feeling blue.";
sglDbl;
dblSgl;

However, you can't include the same quote mark inside the string as is being used to contain them. The following will error, as it confuses the browser as to where the string ends:

var bigmouth = 'I've got no right to take my place...';

Again, the browser gets confused as to where the string ends, and throws an error. This leads us very nicely onto our next subject.

Escaping characters in a string

To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognised as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:

var bigmouth = 'I\'ve got no right to take my place...';
bigmouth;

This works fine. You can escape other characters in the same way, e.g. \",  and there are some special codes besides. See Escape notation for more details.

Concatenating strings

Concatenate is a fancy programming word that means "join together". Joining together strings in JavaScript uses the plus (+) operator, the same one we use to add numbers together, but In this context it does something different. Let's try an example in our console.

var one = 'Hello, ';
var two = 'how are you?';
var joined = one + two;
joined;

The result of this is a variable called joined, which contains the value "Hello, how are you?".

In this instance, we just joined two strings together, but you can do as many as you like, as long as you include a + between each one. Try this:

var multiple = one + one + one + one + two;
multiple;

You can also use a mix of variables and actual strings. Try this:

var response = one + 'I am fine — ' + two;
response;

Note: When you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal.

Concatenation in context

Let's have a look at concatenation being used in action — here's an example from earlier in the course:

<button>Press me</button>
var button = document.querySelector('button');

button.onclick = function() {
  var name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');
}

{{ EmbedLiveSample('Concatenation_in_context', '100%', 50) }}

Here we're using a {{domxref("prompt()", "Window.prompt()")}} function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case name. We then use an {{domxref("alert()", "Window.alert()")}} function in line 5 to display another popup containing a string we've assembled from two string literals and the name variable, via concatenation.

Numbers versus strings

So what happens when we try to add (or concatenate) a string and a number? Let's try it in our console:

'Front ' + 242;

You might expect this to throw an error,  but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as  a string does, so the browser rather cleverly converts the number to a string and concatenates the two strings together.

You can even do this with two numbers — you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the typeof operator to check whether the variable is a number or a string):

var myDate = '19' + '67';
typeof myDate;

If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:

The {{jsxref("Number()")}} object will convert anything passed to it into a number, if it can. Try the following:

var myString = '123';
var myNum = Number(myString);
typeof myNum;

On the other hand, every number has a method called toString() that will convert it to the equivalent string. Try this:

var myNum = 123;
var myString = myNum.toString();
typeof myString;

These constructs can be really useful in some situations, for example if a user enters a number into a form text field it will be a string, but if you want to add it to something say, you'll need it to be a number, so you could pass it through Number() to handle this. We did exactly this in our Number Guessing Game, in line 63.

Useful string methods

Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings. When you create a string, for example by using

var 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 {{jsxref("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 a fresh console. We've provided one below (you can also open this console in a separate tab or window, or use the browser developer console if you'd prefer).

{{ EmbedLiveSample('Hidden_code', '100%', 300) }}

Finding the length of a string

This is easy — you simply use the {{jsxref("length", "String.prototype.length")}} property. Try entering the following lines:

var jobTitle = 'Dogsbody';
jobTitle.length;

This should return the number 8, because "Dogsbody" is 8 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 then 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.

Retrieving a specific string character

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:

jobTitle[0];

Computers count from 0, not 1! 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:

jobTitle[jobTitle.length-1];

The length of "Dogsbody" is 8, but because the count starts at 0, the character position is 7, hence us needing length-1.

You could use this to, for example, find the first letter of a series of strings and order them alphabetically.

Finding a substring inside a string and extracting it

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 {{jsxref("indexOf()", "String.prototype.indexOf()")}} method, which takes a single {{glossary("parameter")}} — the substring you want to search for.

jobTitle.indexOf('body');

This gives us a result of 4, because the substring "body" starts at position 4 (0, 1, 2, 3, 4 — so 5 characters in) inside "Dogsbody". Such code could be used to filter strings, for example say we have a load of web addresses and want to only print out the ones that contain "mozilla"?

This however can be done in another way, which is possibly even more effective. Try the following:

jobTitle.indexOf('zebra');

This should give you a result of -1 — this is returned when the substring is not found in the main string. So you could use this to find all instances of strings that don't contain the substring, or do if you use the negation operator. You could do something like this:

if(jobTitle.indexOf('zebra') !== -1) {
  // do stuff with the string
}

When you know where a substring starts inside a string, {{jsxref("slice()", "String.prototype.slice()")}} can be used to extract it. Try the following:

jobTitle.slice(0,4);

This returns "Dogs" — 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.

Note: The second parameter 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 {{jsxref("slice()", "String.prototype.slice()")}} page to see what else you can find out.

Changing case

The string methods {{jsxref("toLowerCase()", "String.prototype.toLowerCase()")}} and {{jsxref("toUpperCase()", "String.prototype.toUpperCase()")}} take a string and convert all the characters to lower or upper case, 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:

var radData = 'My NaMe Is MuD';
radData.toLowerCase();
radData.toUpperCase();

Updating parts of a string

You can replace one with substring inside a string with another substring using the {{jsxref("replace()", "String.prototype.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:

jobTitle.replace('Dogs','Cats');

Active learning examples

In this section we'll get you to try your handing 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.

Filtering greeting messages

In the first exercise we'll start you off simple — we have an array of greetings 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.

  1. First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you just to test whether it is present?
  2. You'll then need to write a conditional test of the form operand1 operator operand2. Is the thing on the left equal to the the thing on the right? Or in this case, does the method call on the left return the result on the right?
  3. Hint: In this case it is probably more useful to test whether the method call isn't equal to a certain result.

{{ EmbedLiveSample('Playable_code', '100%', 470) }}

Fixing capitalization

In this exercise we have the names of UK cities, 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:

  1. Convert the whole of the string contained in the input variable to lower case 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 replace procedure in another new variable.
  4. Change the value of the 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.

{{ EmbedLiveSample('Playable_code_2', '100%', 450) }}

Making new strings from old parts

In this last exercise the array contains a bunch 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 semi-colon, 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:

  1. Extract the three-letter station code and store it in a new variable.
  2. Find the character index number of the semi-colon.
  3. Extract the human-readable station name using the semi-colon character index number as a reference point, and store it in a new variable.
  4. Concatenate the two new variables and a string literal to make the final string.
  5. Change the value of the result variable to equal to the final string, not the input.

{{ EmbedLiveSample('Playable_code_3', '100%', 450) }}

Conclusion

You can't escape the fact that being able to handle words and sentences in programming is very important — particularly in JavaScript, as web sites 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.

{{PreviousMenuNext("Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

Revision Source

<p>{{draft}}</p>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p>

<div>{{IncludeSubnav("/en-US/Learn")}}</div>

<p class="summary">Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common useful things that you really ought to know when learning JavaScript, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>To gain familiarity with the basics of Maths in JavaScript.</td>
  </tr>
 </tbody>
</table>

<h2 id="The_power_of_words">The power of words</h2>

<p>Words are very important to humans — they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. {{glossary("HTML")}} provides structure and meaning to our text, {{glossary("CSS")}} allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages, showing the right text labels when needed, sorting terms into the desired order, and so much more.</p>

<p>Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.</p>

<h2 id="Strings_—_the_basics">Strings — the basics</h2>

<p>Strings are dealt with in a similar way to numbers at first glance, but you'll start to see some notable differences when you dig deeper. Let's start by entering some basic lines in a console to familiarise ourselves. We've provided one below (you can also <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">open this console</a> in a separate tab or window, or use the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a> if you'd prefer).</p>

<div class="hidden">
<h6 id="Hidden_code">Hidden code</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;JavaScript console&lt;/title&gt;
    &lt;style&gt;
      * {
        box-sizing: border-box;
      }

      html {
        background-color: #0C323D;
        color: #809089;
        font-family: monospace;
      }

      body {
        max-width: 700px;
      }

      p {
        margin: 0;
        width: 1%;
        padding: 0 1%;
        font-size: 16px;
        line-height: 1.5;
        float: left;
      }

      .input p {
        margin-right: 1%;
      }

      .output p {
        width: 100%;
      }

      .input input {
        width: 96%;
        float: left;
        border: none;
        font-size: 16px;
        line-height: 1.5;
        font-family: monospace;
        padding: 0;
        background: #0C323D;
        color: #809089;
      }

      div {
        clear: both;
      }

    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

    
  &lt;/body&gt;

  &lt;script&gt;
    var geval = eval;
    function createInput() {
      var inputDiv = document.createElement('div');
      var inputPara = document.createElement('p');
      var inputForm = document.createElement('input');

      inputDiv.setAttribute('class','input');
      inputPara.textContent = '&gt;';
      inputDiv.appendChild(inputPara);
      inputDiv.appendChild(inputForm);
      document.body.appendChild(inputDiv);

      inputForm.addEventListener('change', executeCode);
    }

    function executeCode(e) {
      try {
        var result = geval(e.target.value);
      } catch(e) {
        var result = 'error — ' + e.message;
      }

      var outputDiv = document.createElement('div');
      var outputPara = document.createElement('p');

      outputDiv.setAttribute('class','output');
      outputPara.textContent = 'Result: ' + result;
      outputDiv.appendChild(outputPara);
      document.body.appendChild(outputDiv);

      e.target.disabled = true;
      e.target.parentNode.style.opacity = '0.5';

      createInput()
    }
    
    createInput();

  &lt;/script&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code', '100%', 300) }}</p>

<h3 id="Creating_a_string">Creating a string</h3>

<p>To start with, enter the following lines:</p>

<pre class="brush: js">
var string = 'The revolution will not be televised.';
string;</pre>

<p>Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.</p>

<p>If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:</p>

<pre class="brush: js example-bad">
var badString = This is a test;
var badString = 'This is a test;
var badString = This is a test';</pre>

<p>These lines don't work because any text string without quotes around it is assumed to be a variable name, property name, reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing ; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.</p>

<p>The following will work if you previously defined the variable <code>string</code> — try it now:</p>

<pre class="brush: js">
var badString = string;
badString;</pre>

<p><code>badString</code> is now set to have the same value as <code>string</code>.</p>

<h3 id="Single_quotes_versus_double_quotes">Single quotes versus double quotes</h3>

<p>In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work ok:</p>

<pre class="brush: js">
var sgl = 'Single quotes.'
var dbl = "Double quotes";
sgl;
dbl;</pre>

<p>There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it however, differently quoted code can be confusing, especially if you use the different quotes on the same string! The following will return an error:</p>

<pre class="brush: js example-bad">
var badQuotes = 'What on earth?";</pre>

<p>The browser will think the string has not been closed, because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are ok:</p>

<pre>
var sglDbl = 'Would you eat a "fish supper"?'
var dblSgl = "I'm feeling blue.";
sglDbl;
dblSgl;</pre>

<p>However, you can't include the same quote mark inside the string as is being used to contain them. The following will error, as it confuses the browser as to where the string ends:</p>

<pre class="brush: js example-bad">
var bigmouth = 'I've got no right to take my place...';</pre>

<p>Again, the browser gets confused as to where the string ends, and throws an error. This leads us very nicely onto our next subject.</p>

<h3 id="Escaping_characters_in_a_string">Escaping characters in a string</h3>

<p>To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognised as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:</p>

<pre class="brush: js">
var bigmouth = 'I\'ve got no right to take my place...';
bigmouth;</pre>

<p>This works fine. You can escape other characters in the same way, e.g. <code>\"</code>,&nbsp; and there are some special codes besides. See <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation">Escape notation</a> for more details.</p>

<h2 id="Concatenating_strings">Concatenating strings</h2>

<p>Concatenate is a fancy programming word that means "join together". Joining together strings in JavaScript uses the plus (+) operator, the same one we use to add numbers together, but In this context it does something different. Let's try an example in our console.</p>

<pre class="brush: js">
var one = 'Hello, ';
var two = 'how are you?';
var joined = one + two;
joined;</pre>

<p>The result of this is a variable called <code>joined</code>, which contains the value "Hello, how are you?".</p>

<p>In this instance, we just joined two strings together, but you can do as many as you like, as long as you include a <code>+</code> between each one. Try this:</p>

<pre class="brush: js">
var multiple = one + one + one + one + two;
multiple;</pre>

<p>You can also use a mix of variables and actual strings. Try this:</p>

<pre class="brush: js">
var response = one + 'I am fine — ' + two;
response;</pre>

<div class="note">
<p><strong>Note</strong>: When you enter an actual string in your code, enclosed in single or double quotes, it is called a <strong>string literal</strong>.</p>
</div>

<h3 id="Concatenation_in_context">Concatenation in context</h3>

<p>Let's have a look at concatenation being used in action — here's an example from earlier in the course:</p>

<pre class="brush: html">
&lt;button&gt;Press me&lt;/button&gt;</pre>

<pre class="brush: js">
var button = document.querySelector('button');

button.onclick = function() {
  var name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');
}</pre>

<p>{{ EmbedLiveSample('Concatenation_in_context', '100%', 50) }}</p>

<p>Here we're using a {{domxref("prompt()", "Window.prompt()")}} function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case <code>name</code>. We then use an {{domxref("alert()", "Window.alert()")}} function in line 5 to display another popup containing a string we've assembled from two string literals and the <code>name</code> variable, via concatenation.</p>

<h3 id="Numbers_versus_strings">Numbers versus strings</h3>

<p>So what happens when we try to add (or concatenate) a string and a number? Let's try it in our console:</p>

<pre class="brush: js">
'Front ' + 242;
</pre>

<p>You might expect this to throw an error,&nbsp; but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as&nbsp; a string does, so the browser rather cleverly converts the number to a string and concatenates the two strings together.</p>

<p>You can even do this with two numbers — you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the <code>typeof</code> operator to check whether the variable is a number or a string):</p>

<pre class="brush: js">
var myDate = '19' + '67';
typeof myDate;</pre>

<p>If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:</p>

<p>The {{jsxref("Number()")}} object will convert anything passed to it into a number, if it can. Try the following:</p>

<pre class="brush: js">
var myString = '123';
var myNum = Number(myString);
typeof myNum;</pre>

<p>On the other hand, every number has a method called <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString">toString()</a></code> that will convert it to the equivalent string. Try this:</p>

<pre class="brush: js">
var myNum = 123;
var myString = myNum.toString();
typeof myString;</pre>

<p>These constructs can be really useful in some situations, for example if a user enters a number into a form text field it will be a string, but if you want to add it to something say, you'll need it to be a number, so you could pass it through <code>Number()</code> to handle this. We did exactly this in our <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html#L63">Number Guessing Game, in line 63</a>.</p>

<h2 id="Useful_string_methods">Useful string methods</h2>

<p>Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings. When you create a string, for example by using</p>

<pre class="brush: js">
var string = 'This is my string';</pre>

<p>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 {{jsxref("String")}} object page and look down the list on the side of the page!</p>

<p><strong>Now, before your brain starts melting, don't worry!</strong> 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.&nbsp;</p>

<p>Let's enter some examples into a fresh console. We've provided one below (you can also <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">open this console</a> in a separate tab or window, or use the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a> if you'd prefer).</p>

<div class="hidden">
<h6 id="Hidden_code_2">Hidden code</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;JavaScript console&lt;/title&gt;
    &lt;style&gt;
      * {
        box-sizing: border-box;
      }

      html {
        background-color: #0C323D;
        color: #809089;
        font-family: monospace;
      }

      body {
        max-width: 700px;
      }

      p {
        margin: 0;
        width: 1%;
        padding: 0 1%;
        font-size: 16px;
        line-height: 1.5;
        float: left;
      }

      .input p {
        margin-right: 1%;
      }

      .output p {
        width: 100%;
      }

      .input input {
        width: 96%;
        float: left;
        border: none;
        font-size: 16px;
        line-height: 1.5;
        font-family: monospace;
        padding: 0;
        background: #0C323D;
        color: #809089;
      }

      div {
        clear: both;
      }

    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

    
  &lt;/body&gt;

  &lt;script&gt;
    var geval = eval;
    function createInput() {
      var inputDiv = document.createElement('div');
      var inputPara = document.createElement('p');
      var inputForm = document.createElement('input');

      inputDiv.setAttribute('class','input');
      inputPara.textContent = '&gt;';
      inputDiv.appendChild(inputPara);
      inputDiv.appendChild(inputForm);
      document.body.appendChild(inputDiv);

      inputForm.addEventListener('change', executeCode);
    }

    function executeCode(e) {
      try {
        var result = geval(e.target.value);
      } catch(e) {
        var result = 'error — ' + e.message;
      }

      var outputDiv = document.createElement('div');
      var outputPara = document.createElement('p');

      outputDiv.setAttribute('class','output');
      outputPara.textContent = 'Result: ' + result;
      outputDiv.appendChild(outputPara);
      document.body.appendChild(outputDiv);

      e.target.disabled = true;
      e.target.parentNode.style.opacity = '0.5';

      createInput()
    }
    
    createInput();

  &lt;/script&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code', '100%', 300) }}</p>

<h3 id="Finding_the_length_of_a_string">Finding the length of a string</h3>

<p>This is easy — you simply use the {{jsxref("length", "String.prototype.length")}} property. Try entering the following lines:</p>

<pre class="brush: js">
var jobTitle = 'Dogsbody';
jobTitle.length;</pre>

<p>This should return the number 8, because "Dogsbody" is 8 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 then 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.</p>

<h3 id="Retrieving_a_specific_string_character">Retrieving a specific string character</h3>

<p>On a related note, you can return any character inside a string by using <strong>square bracket notation</strong> — this means you include square brackets (<code>[]</code>) 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:</p>

<pre class="brush: js">
jobTitle[0];</pre>

<p>Computers count from 0, not 1! To retrieve the last character of <em>any</em> string, we could use the following line, combining this technique with the <code>length</code> property we looked at above:</p>

<pre class="brush: js">
jobTitle[jobTitle.length-1];</pre>

<p>The length of "Dogsbody" is 8, but because the count starts at 0, the character position is 7, hence us needing <code>length-1</code>.</p>

<p>You could use this to, for example, find the first letter of a series of strings and order them alphabetically.</p>

<h3 id="Finding_a_substring_inside_a_string_and_extracting_it">Finding a substring inside a string and extracting it</h3>

<p>Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say <em>if a substring is present inside a string</em>). This can be done using the {{jsxref("indexOf()", "String.prototype.indexOf()")}} method, which takes a single {{glossary("parameter")}} — the substring you want to search for.</p>

<pre class="brush: js">
jobTitle.indexOf('body');</pre>

<p>This gives us a result of 4, because the substring "body" starts at position 4 (0, 1, 2, 3, 4 — so 5 characters in) inside "Dogsbody". Such code could be used to filter strings, for example say we have a load of web addresses and want to only print out the ones that contain "mozilla"?</p>

<p>This however can be done in another way, which is possibly even more effective. Try the following:</p>

<pre class="brush: js">
jobTitle.indexOf('zebra');</pre>

<p>This should give you a result of <code>-1</code> — this is returned when the substring is not found in the main string. So you could use this to find all instances of strings that <strong>don't</strong> contain the substring, or do if you use the negation operator. You could do something like this:</p>

<pre class="brush: js">
if(jobTitle.indexOf('zebra') !== -1) {
  // do stuff with the string
}</pre>

<p>When you know where a substring starts inside a string, {{jsxref("slice()", "String.prototype.slice()")}} can be used to extract it. Try the following:</p>

<pre class="brush: js">
jobTitle.slice(0,4);</pre>

<p>This returns "Dogs" — 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.</p>

<div class="note">
<p><strong>Note</strong>: The second parameter 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 {{jsxref("slice()", "String.prototype.slice()")}} page to see what else you can find out.</p>
</div>

<h3 id="Changing_case">Changing case</h3>

<p>The string methods {{jsxref("toLowerCase()", "String.prototype.toLowerCase()")}} and {{jsxref("toUpperCase()", "String.prototype.toUpperCase()")}} take a string and convert all the characters to lower or upper case, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.</p>

<p>Let's try entering the following lines to see what happens:</p>

<pre class="brush: js">
var radData = 'My NaMe Is MuD';
radData.toLowerCase();
radData.toUpperCase();</pre>

<h3 id="Updating_parts_of_a_string">Updating parts of a string</h3>

<p>You can replace one with substring inside a string with another substring using the {{jsxref("replace()", "String.prototype.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.</p>

<p>It takes two parameters — the string you want to replace, and the string you want to replace it with. Try this example:</p>

<pre class="brush: js">
jobTitle.replace('Dogs','Cats');</pre>

<h2 id="Active_learning_examples">Active learning examples</h2>

<p>In this section we'll get you to try your handing 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.</p>

<p>Each example comes with a <em>Reset</em> button, which you can use to reset the code if you make a mistake and can't get it working again, and a <em>Show solution</em> button you can press to see a potential answer if you get really stuck.</p>

<h3 id="Filtering_greeting_messages">Filtering greeting messages</h3>

<p>In the first exercise we'll start you off simple — we have an array of greetings 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 <code>if( ... )</code> structure, to test each string and only print it in the list if it is a Christmas message.</p>

<ol>
 <li>First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you just to test whether it is present?</li>
 <li>You'll then need to write a conditional test of the form <em>operand1 operator operand2</em>. Is the thing on the left equal to the the thing on the right? Or in this case, does the method call on the left return the result on the right?</li>
 <li>Hint: In this case it is probably more useful to test whether the method call <em>isn't</em> equal to a certain result.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code">Playable code</h6>

<pre class="brush: html">
&lt;div class="output" style="min-height: 125px;"&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 270px;"&gt;
var list = document.querySelector('.output ul');
list.innerHTML = '';
var greetings = ['Happy Birthday!',
                 'Merry Christmas my love',
                 'A happy Christmas to all the family',
                 'You\'re all I want for Christmas',
                 'Get well soon'];

for(i = 0; i &lt; greetings.length; i++) {
  var input = greetings[i];
  // Your conditional test needs to go inside the parentheses in the line below, replacing what's currently there
  if(greetings[i]) {
    var result = input;
    var listItem = document.createElement('li');
    listItem.textContent = result;
    list.appendChild(listItem);
  }
}
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar greetings = [\'Happy Birthday!\',\n                 \'Merry Christmas my love\',\n                 \'A happy Christmas to all the family\',\n                 \'You\\\'re all I want for Christmas\',\n                 \'Get well soon\'];\n\nfor(i = 0; i &lt; greetings.length; i++) {\n  var input = greetings[i];\n  if(greetings[i].indexOf(\'Christmas\') !== -1) {\n    var result = input;\n    var listItem = document.createElement(\'li\');\n    listItem.textContent = result;\n    list.appendChild(listItem);\n  }\n}';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code', '100%', 470) }}</p>

<h3 id="Fixing_capitalization">Fixing capitalization</h3>

<p>In this exercise we have the names of UK cities, 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:</p>

<ol>
 <li>Convert the whole of the string contained in the <code>input</code> variable to lower case and store it in a new variable.</li>
 <li>Grab the first letter of the string in this new variable and store it in another variable.</li>
 <li>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 replace procedure in another new variable.</li>
 <li>Change the value of the <code>result</code> variable to equal to the final result, not the <code>input</code>.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: 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.</p>
</div>

<div class="hidden">
<h6 id="Playable_code_2">Playable code 2</h6>

<pre class="brush: html">
&lt;div class="output" style="min-height: 125px;"&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 250px;"&gt;
var list = document.querySelector('.output ul');
list.innerHTML = '';
var cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
for(i = 0; i &lt; cities.length; i++) {
  var input = cities[i];
  // write your code just below here

  var result = input;
  var listItem = document.createElement('li');
  listItem.textContent = result;
  list.appendChild(listItem);
}
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar cities = [\'lonDon\', \'ManCHESTer\', \'BiRmiNGHAM\', \'liVERpoOL\'];\n\nfor(i = 0; i &lt; cities.length; i++) {\n  var input = cities[i];\n  var lower = input.toLowerCase();\n  var firstLetter = lower.slice(0,1);\n  var capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());\n  var result = capitalized;\n  var listItem = document.createElement(\'li\');\n  listItem.textContent = result;\n  list.appendChild(listItem);\n\n}';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code_2', '100%', 450) }}</p>

<h3 id="Fixing_capitalization">Making new strings from old parts</h3>

<p>In this last exercise the array contains a bunch 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 semi-colon, followed by the human-readable station name. For example:</p>

<pre>
MAN675847583748sjt567654;Manchester Piccadilly</pre>

<p>We want to extract the station code and name, and put them together in a&nbsp; string with the following structure:</p>

<pre>
MAN: Manchester Piccadilly</pre>

<p>We'd recommend doing it like this:</p>

<ol>
 <li>Extract the three-letter station code and store it in a new variable.</li>
 <li>Find the character index number of the semi-colon.</li>
 <li>Extract the human-readable station name using the semi-colon character index number as a reference point, and store it in a new variable.</li>
 <li>Concatenate the two new variables and a string literal to make the final string.</li>
 <li>Change the value of the <code>result</code> variable to equal to the final string, not the <code>input</code>.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code_3">Playable code 3</h6>

<pre class="brush: html">
&lt;div class="output" style="min-height: 125px;"&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 250px;"&gt;
var list = document.querySelector('.output ul');
list.innerHTML = '';
var stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
                'GNF576746573fhdg4737dh4;Greenfield',
                'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
                'SYB4f65hf75f736463;Stalybridge',
                'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];

for(i = 0; i &lt; stations.length; i++) {
  var input = stations[i];
  // write your code just below here   

  var result = input;
  var listItem = document.createElement('li');
  listItem.textContent = result;
  list.appendChild(listItem);
}
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar stations = [\'MAN675847583748sjt567654;Manchester Piccadilly\',\n                \'GNF576746573fhdg4737dh4;Greenfield\',\n                \'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street\',\n                \'SYB4f65hf75f736463;Stalybridge\',\n                \'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield\'];\n\nfor(i = 0; i &lt; stations.length; i++) {\n  var input = stations[i];\n  var code = input.slice(0,3);\n  var semiC = input.indexOf(\';\');\n  var name = input.slice(semiC + 1);\n  var final = code + \': \' + name;\n  var result = final;\n var listItem = document.createElement(\'li\');\n  listItem.textContent = result;\n  list.appendChild(listItem);\n}';


textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code_3', '100%', 450) }}</p>

<h2 id="Conclusion">Conclusion</h2>

<p>You can't escape the fact that being able to handle words and sentences in programming is very important — particularly in JavaScript, as web sites 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.</p>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p>
Revert to this revision