Introduction To Programming
10-152-310

Learning Plan 2 : Variables and Data Types

String Variables

We have to process lots of strings in programs a lot too.

  • Strings are a series of characters surrounded by double or single quotes.
    "This is a string"
    "This isn't a number"
    'This is a string too'
    'The cow says, "moo"'
    "Fred"
    "Bert"
    "Ernie"
  • You have to have quotes around a string.
    • If a string is surrounded by double quotes then you can have single quotes inside the string.
    • If a string is surrounded by single quotes then you can have double quotes inside the string.
    • But, sometimes we need to put a character into a string that is special, like a tab. How do we do that?
  • Escape Characters. Here's a list of characters that we need to be able to embed into strings
\b Backspace
\t tab
\n newline
\v vertical tab
\f form feed
\r Carriage return
\\ Literal backslash
\" Double Quote
\' Single Quote
  • To embed them in a string you just type the code with the backslash.
                    
                  

Escape Character Examples

  • Adding a single quote to a string that starts and ends with single quotes.
                        
                    
  • Adding a double quote to a string that starts and ends with double quotes.
                        
                    
  • Adding both and single and a double quote to the same string.
                        
                    
  • Here's some strings with tabs
                        
                    

The length function.

  • There are lots of functions in JavaScript that let us manipulate strings.
  • Length of a string: You use the ".length" function
                        
                    
  • Here's the output from the above code:
    The mystery variable is 16

Here's the working demo of the above code: Demo: String Variables