# Strings (Text)

## Strings and Chars

Every letter or punctuation mark typed from the keyboard is called a **character**. Many characters together create a **string** of text. \
**For Example:** The word `hello` is a *string* made of the *characters* `'h' 'e' 'l' 'l' 'o'`.

`"This is a string"`    |    `'This is a string'`    |    `` `This is a string` ``

**Strings** are a special *type* of variable called an **`object`**. Similar to a pencil, objects in code have properties (colour, length, weight) and methods (write, erase). A string is a bunch of chars put together (like a on a string, get it?) and has a length as well as some methods. Another term for this special object is an [`Array`](/unit-2/variables/arrays.md).\
\
**For Example:** the separate characters `'h' 'e' 'l' 'l' 'o'` can be *strung* together to make `"hello"`.

We will have an entire lesson on [***arrays***](/unit-2/variables/arrays.md) but what you need to know is that you can access each individual letter (character) in a string because they each have an index (like a home address) **starting at zero**.

```javascript
let someString = "Sample string FTW!";
console.log(someString[0]);     // Prints 'S'
console.log(someString[5]);     // Prints 'e'
console.log(someString.length); // Prints the length - 18
```

## Special Characters

New lines, quotes, and tabs are all examples of text that needs to be *escaped*. You need to use the slash character (`\`) to tell the interpreter that there is a special circumstance.

| **Escape Sequence** | **Name**                 | **Symbol** |
| ------------------- | ------------------------ | ---------- |
| **`\b`**            | backspace                | \<BS>      |
| **`\t`**            | horizontal tab           | \<HT>      |
| **`\n`**            | line feed (**new line**) | \<LF>      |
| **`\v`**            | vertical tab             | \<VT>      |
| **`\f`**            | form feed                | \<FF>      |
| **`\r`**            | carriage return          | \<CR>      |
| **`\"`**            | double quote             | **`"`**    |
| **`\'`**            | single quote             | **`'`**    |
| **`\\`**            | backslash                | **`\`**    |

> The above table was shamefully *borrowed* from <http://es5.github.io/x7.html#x7.8.4> (table 4)

![Use escape sequences to print special characters](/files/-LPvzWd7QnH_EPHTDmib)

### **Example**

```javascript
let myOutput = "This is a single line but\nthis is a completely new line";
console.log(myOutput);
console.log("I used \"\\n\" to create the new line");
/* Output:
This is a single line but
this is a completely new line
I used "\n" to create the new line
*/
```

## **Concatenation**

**The `+` operator** performs string concatenation (add one string to the end of another) as long as one of the items is already a string. This means it combines letters together: `'ab' + 'c' = 'abc'`

**Example**:

```javascript
let myString = "She sold ";
console.log(myString + 17 + " sea shells.");

// Output:   She sold 17 sea shells.
```

You can also use `+=` like this:

```javascript
var greeting = "Hello";
var world = " World!";

greeting += world;

// This sets the value of myString to "Hello World!"
```

The above is an abbreviation for `greeting = greeting + world;`

## Template Literals

[Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) take a bit of getting used to but they are a great way to work with Strings in JS. First of all, you don't need to worry about escaping the `"` or `'` characters. You don't need `\n` for a new line if you simply put your string one multiple lines. Finally, you can get away from using the `+` symbol for concatenation and insert your variables into the string using `${variable}`. It makes for more readable code, which is important.\
\
**Example**:

{% embed url="<https://repl.it/repls/RegalExtrasmallRam>" %}

## Examples

### Basic String Work

{% embed url="<https://tech.io/snippet/N9VrPwP>" %}

### Built-in Functions

Strings in Javascript, Java, and Python have a bunch of special functions that you can use to search or replace text. Let's take the string "Goodbye Sunshine!" and examine what we can do in Javascript (feel free to play around):

{% embed url="<https://repl.it/repls/AgileFatLanservers>" %}
Play around with strings. Get used to their methods and functionalities.
{% endembed %}

## Important Note

Aside from `.length` (which is a *property* of the string), you can manipulate or do many things with some pretty awesome [built-in functions](<  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods_2&#xA;>). It is worth researching these functions in order to program efficiently. However, there will be many assignments in our course where you will not be permitted to use the built-in functions. This is to force you to think like a programmer - remember, this is an introductory course.

The assignments will state, in the description, what is permitted.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.brash.ca/unit-2/variables/strings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
