JavaScript – Beginning to work with strings

Strings are used all over the place, at first they can be pretty weird, and working with the quotation marks can be finicky, and cumbersome. Strings are mainly used to store, manipulate, and interact with text. Strings, like numbers, are actually very complicated the more you learn about them, but for now we will keep it as simple as possible. If you do not have your console set up, make sure read Getting Started with JavaScript.

I am string!

'I am a string!'
"I am a string as well, with double quotes!"

To create a string, or, more accurately, a string literal in JavaScript, we write some text and put it inside a pair of either ' single quotes, or " double quotes. In JavaScript, strings, arrays, and objects all have these characters that start and end a data type. Arrays use [ and ], objects use { and }. When you see quotes in JavaScript there is most likely a string starting or ending. If you see the square brackets you are dealing with an array, and the curly braces are usually an object.

Working with strings

Strings like numbers also have operators that we can use. For example, if we had 'Hi, my name is ' and 'Edwin', how would we combine these into a single string? Go to the console and type in the following and hit enter:

'Hi, my name is ' + 'Edwin'

The output value from the console is now just one string; 'Hi, my name is Edwin'. This becomes a handy way of combining messages together, and is often referred to as string concatenation. Strings are also a series of characters so we can find out which letter is at each point like this. Take note of the pattern we write String.charAt(position)

'Cat'.charAt(0)
// Outputs "C"

'Cat'.charAt(1)
// Outputs "a"

'Cat'.charAt(2)
// Outputs "t"

'Cat'.charAt(3)
// Outputs ""

0 is the starting point in our series of letters. It may be weird to access the first character at 0, but this is a fairly common convention across all programming languages, and it has its benefits. We can also access characters using a different syntax:

'Cat'[0]
// Outputs "C"

'Cat'[1]
// Outputs "a"

'Cat'[2]
// Outputs "t"

'Cat'[3]
// Outputs undefined

This is another way to find what character is at a certain position in the string. This time when we go to an empty position we get undefined, instead of an empty string. This is the main difference between these two access methods.

Empty strings

As seen above we see "" as one of the values returned. This is an empty string, same for ''. Empty strings hold can hold special meanings in JavaScript, which we will explore at another time. An empty string is still a string, it just lacks any characters. When we look at the length, ''.length we get 0.

( '' + 'Hi!' ).length
// Outputs 3, first we add together the empty string and Hi! to get a new string 'Hi!' which has three characters in it.

Strings are a special kind of array

In JavaScript, strings in some ways can be treated as a special kind of array. An array is a list of values like: [ 1, 2, 3 ]. Arrays have a similar lookup syntax to the string we used earlier. In fact the string character lookup is the array lookup syntax. Try the following in your console.

[ 'C', 'a', 't' ][0]
// Outputs "C" same as 'Cat'[0]

[ 'C', 'a', 't' ][1]
// Outputs "a" same as 'Cat'[1]

[ 'C', 'a', 't' ][2]
// Outputs "t" same as 'Cat'[2]

[ 'C', 'a', 't' ][3]
// Outputs undefined same as 'Cat'[3]

So strings are a much more human friendly way to interact with text in a programming language. We don’t have the brackets, commas etc. Although arrays and strings share similarities, they are definitely their own thing, and are used for different purposes. We can go back and forth between string and array form using the split and join methods.

'Cat'.split('')
// Outputs [ 'C', 'a', 't' ]

[ 'C', 'a', 't' ].join('')
// Outputs 'Cat'

We use split, a string method, to separate the string into an array. We use an empty string '' as the split piece, causing each letter to become its own part of the array.

We then work backwards going from the array and calling join, an array method, to crunch the array back into a string. We can join the array using a different string as well like this:

[ 'I', 'am', 'happy!' ].join( ' ' )
// Outputs "I am happy!"

'AATCCGCTAG'.split('').join('G')
// Outputs "AGAGTGCGCGGGCGTGAGG"

We see in the first example that each string part gets joined together with a space. making a sentence. In the next example we see something much more interesting. A series of nucleotide notations are being split into an array, and we are joining back together with in a G between each letter; in effect editing the genome sequence! 😲 Fiddling around with basic strings can lead to astounding real world applications.

Things to watch out for

Strings are usually pretty easy to work with until you get to one major problem, what if we have a string like this:

'JavaScript, it's amazing!'
// Outputs a syntax error? What's going on!

We get our first syntax error: Uncaught SyntaxError: Unexpected identifier. Error messages can be daunting, but if you ever see a syntax error, it means that we have typed in invalid JavaScript. The problem we have above, is that the ' is inside our quote as well as what we are using to start the string. JavaScript see the string 'JavaScript, it', and from there goes kaput because s amazing!' is not valid JavaScript. To properly have a string with a quote inside of it there are two options, escaping and using different outer quotes:

// Escaping
'JavaScript, it\'s amazing!'

// Different outer quotes.
"JavaScript, it's amazing!"

The \ escapes the ' allowing it to not be processed by JavaScript as part of the string bounds, and instead as the character '. Escaping gets real confusing really quickly, what if we wanted to have the string:

'To escape a ' in JavaScript you need to use \''
// Syntax error.

// With escaping.
'To escape a \' in JavaScript you need to use \''
// Outputs "To escape a ' in JavaScript you need to use '"
// Not what we want yet.

// Escaping the escape
'To escape a \' in JavaScript you need to use \\\''
// Outputs "To escape a ' in JavaScript you need to use \'"
// Yay!

So escaping can get very tricky and is often a big headache. It also has a weird name. To better think of escaping, we are escaping how JavaScript would normally process a string, and using the \ to signify that the next character should be interpreted by JavaScript as an actual character. Don’t worry about escaping too much, but it is good to be aware of it. For the most part not too many issues will be encountered.

Basics of strings in JavaScript

Strings are a basic data type in JavaScript used to interact with text. They are essentially a list of characters in sequence. Strings have a lot of hidden secrets lurking within, but for the most part you will only use them as a means of interacting with text. Even as a basic data type, there is a lot of power for our imaginations to run wild with.

Getting Started with JavaScript

JavaScript is a widespread programming language. Oddly enough, using a Web Browser like Chrome, Firefox or Brave is a great way to start learning JavaScript. Download one of these browsers and we can get started almost immediately after opening it up. For our examples we will be using Chrome, as it is currently the most widely used web browser.

Why JavaScript?

There is so much that you can do with JavaScript. You can make pasta fall from the skycreate a todo list, or go wherever your heart takes you. JavaScript is a key part of how you interact with websites. If you aren’t sold yet, try reading this post: Why should I learn JavaScript.

Setting Up

The first step is to download and set up a browser, if you are reading this post you have likely already done this. Hopefully you are using a browser mentioned at the start; Chrome. Create a new window and we will open up a hidden part of the browser; the console. The console can be accessed by going to Menu > More Tools > Developer Tools and clicking, or by using the keyboard shortcuts: Ctrl + Shift + J (Windows), Cmd + Option + J (Mac). Once you have the console open it should look something like this.

Google Chrome with dev tools open.

Using the console

Now we have the developer tools open and with the Console tab active. We can now start to use JavaScript to directly interact with our browser window! Type the following into the console and hit enter when you are done:

document.write('Hi!');

This will make windows content contain the text “Hi!”. Try changing the message. Type in the following code and hit enter at the console:

document.write(' I am learning and using JavaScript!');

Now the “Hi!” is followed by the new message. Pretty neat. We have used the console to interact with our browser window. Realistically you are not going to use document.write very often, if at all. Now we are going to use the console to further explore the basics of JavaScript.

Working in the console

You might have noticed that after we typed our document.write commands we get an undefined message in the console below each command. When we type and execute commands in the console we get an output back out. When we run document.write, it does not return anything, so the console shows undefined. If we type 1 into the console and hit enter let’s see what the output value ends up as.

Outputting 1 on the console.

As expected we get 1. Now we can do simple addition try:

11 + 11

We get an output of 22. There are some basic math operators we can use in JavaScript

  • Addition: 2 + 2
    • Outputs 4
  • Subtraction: 3 – 2
    • Outputs 1
  • Multiplication: 3 * 2
    • Outputs 6
  • Division: 6 / 2
    • Outputs 3

Working with decimals and other numbers can get a bit weird in JavaScript, so we will not go into too much depth for now. These numbers are a primitive data type in JavaScript, the other main types you will work with are strings, arrays, objects, and functions. Here is what each looks like in code.

  • String
    • 'Hi, I am a string!'
  • Array
    • [ 1, 2, 3, ]
  • Object
    • { is: 'Object' }
  • Function
    • function get10 () { return 10; }

Together these five primitives will be almost all you ever use in JavaScript. The challenge in JavaScript is figuring out how to arrange each of these pieces to create and explore your vision.