• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Learn web development
  1. MDN
  2. Learn web development
  3. JavaScript
  4. JavaScript first steps
  5. Handling text — strings in JavaScript

Handling text — strings in JavaScript

In This Article
  1. The power of words
  2. Strings — the basics
    1. Creating a string
    2. Single quotes versus double quotes
    3. Escaping characters in a string
  3. Concatenating strings
    1. Concatenation in context
    2. Numbers versus strings
  4. Conclusion
Previous Overview: First steps Next

 

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 things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.

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 strings 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. HTML provides structure and meaning to our text, 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 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 similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into a console to familiarize 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).

Hidden code
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JavaScript console</title>
    <style>
      * {
        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;
      }
    </style>
  </head>
  <body>
  </body>
  <script>
    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 = '>';
      inputDiv.appendChild(inputPara);
      inputDiv.appendChild(inputForm);
      document.body.appendChild(inputDiv);
      if(document.querySelectorAll('div').length > 1) {
        inputForm.focus();
      }
      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();
  </script>
</html>

Creating a string

  1. 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.
  2. 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.
  3. 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

  1. In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay:
    var sgl = 'Single quotes.';
    var dbl = "Double quotes";
    sgl;
    dbl;
  2. 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?";
  3. 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 okay:
    var sglDbl = 'Would you eat a "fish supper"?';
    var dblSgl = "I'm feeling blue.";
    sglDbl;
    dblSgl;
  4. However, you can't include the same quote mark inside the string if it's 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...';
    This leads us very nicely into 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 recognized 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

  1. 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?".
  2. In the last 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;
  3. 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!');
}

Here we're using a 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 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

  1. 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.
  2. 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;
  3. 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 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. However, if you want to add this number to something, 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.

Conclusion

So that's the very basics of strings covered in JavaScript. In the next article we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.

Previous Overview: First steps Next

 

Document Tags and Contributors

Tags: 
  • Article
  • Beginner
  • CodingScripting
  • concatenation
  • Guide
  • JavaScript
  • Join
  • l10n:priority
  • Quotes
  • strings
 Contributors to this page: chrisdavidmills, hadleyel, shoelaces, Jeremie, Sebastianz, fscholz
 Last updated by: chrisdavidmills, Jun 21, 2017, 1:08:50 AM
See also
  1. Complete beginners start here!
  2. Getting started with the Web
    1. Getting started with the Web overview
    2. Installing basic software
    3. What will your website look like?
    4. Dealing with files
    5. HTML basics
    6. CSS basics
    7. JavaScript basics
    8. Publishing your website
    9. How the Web works
  3. HTML — Structuring the Web
  4. Introduction to HTML
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. Multimedia and embedding
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML tables
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. Introduction to CSS
    1. Introduction to CSS overview
    2. How CSS works
    3. CSS syntax
    4. Selectors introduction
    5. Simple selectors
    6. Attribute selectors
    7. Pseudo-classes and pseudo-elements
    8. Combinators and multiple selectors
    9. CSS values and units
    10. Cascade and inheritance
    11. The box model
    12. Debugging CSS
    13. Assessment: Fundamental CSS comprehension
  9. Styling text
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  10. Styling boxes
    1. Styling boxes overview
    2. Box model recap
    3. Backgrounds
    4. Borders
    5. Styling tables
    6. Advanced box effects
    7. Assessment: Creating fancy letterheaded paper
    8. Assessment: A cool-looking box
  11. CSS layout
    1. CSS layout overview
    2. Introduction
    3. Floats
    4. Positioning
    5. Practical positioning examples
    6. Flexbox
    7. Grids
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript first steps
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. Arrays
    10. Assessment: Silly story generator
  14. JavaScript building blocks
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. Introduction to events
    8. Assessment: Image gallery
  15. Introducing JavaScript objects
    1. Introducing JavaScript objects overview
    2. Object basics
    3. Object-oriented JavaScript for beginners
    4. Object prototypes
    5. Inheritance in JavaScript
    6. Working with JSON data
    7. Object building practise
    8. Assessment: Adding features to our bouncing balls demo
  16. Accessibility — Make the web usable by everyone
  17. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  18. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  19. Tools and testing
  20. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  21. Server-side website programming
  22. First steps
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  23. Django web framework (Python)
    1. Django web framework (Python) overview
    2. Introduction
    3. Setting up a development environment
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  24. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  25. Further resources
  26. Advanced learning material
    1. WebGL: Graphics processing
  27. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. How the Web works
    5. Tools and setup
    6. Design and accessibility
  28. How to contribute