What are 'strings' ? 🤔
Tags: javascript, beginners, codenewbie
Published: 2020-07-29 12:32:07

A `string` is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.

As strings are the way we display and work with text, and text is our main way of communicating and understanding through computers, strings are one of the most fundamental concepts of programming to be familiar with.

<b>Creating and Viewing the Output of Strings </b>

In JavaScript, there are three ways to write a string — they can be written inside single quotes` (' ')`, double quotes `(" ")`, or backticks `(` `)`. The type of quote used must match on both sides, however it is possible that all three styles can be used throughout the same script.

Strings using double quotes and single quotes are effectively the same. As there is no convention or official preference for single- or double-quoted strings, all that matters is keeping consistent within project program files.

```javascript
'This string uses single quotes.';
```
```javascript
"This string uses double quotes.";
```
The third and newest way to create a string is called a template literal. Template literals use the backtick (also known as a grave accent) and work the same way as regular strings with a few additional bonuses, which we will cover in this article.

```javascript
`This string uses backticks.`;
```
The easiest way to view the output of a string is to print it to the console, with ` console.log() `:
```javascript
console.log("This is a string in the console.");

```
```js
Output
This is a string in the console.
```
Another simple way to output a value is to send an alert popup to the browser with `alert()`:

```javascript
alert("This is a string in an alert.");
```
`alert() `is a less common method of testing and viewing output, as it can quickly become tedious to close the alerts.

<b>Storing a String in a Variable</b>

Variables in JavaScript are named containers that store a value, using the keywords var, const or let. We can assign the value of a string to a named variable.
```js
const newString = "This is a string assigned to a variable.";
```
Now that the newString variable contains a string, we can reference it and print it to the console.
```js
console.log(newString);
```
This will output the string value.
```js
Output
This is a string assigned to a variable.
```

🛑 Using variables to stand in for `strings`, it is not necessary  to retype a string each time we want to use it, making it simpler for us to work with and manipulate strings within our programs.

<b>String Concatenation</b>

🛑 Concatenation means joining two or more strings together to create a new string. In order to concatenate, we use the concatenation operator, represented by a + symbol. The + symbol is also the addition operator when used with arithmetic operations.
👉 There are 3 ways to concatenate strings in JavaScript. In this tutorial, you'll the different ways and the tradeoffs between them.
<b>The `+` Operator </b>
👉 The same` +` operator you use for adding two numbers can be used to concatenate two strings.
```js
const str = 'Hello' + ' ' + 'World';
str; // 'Hello World'
```
👉 You can also use `+= `, where `a += b` is a shorthand for `a = a + b`.
```js
let str = 'Hello';
str += ' ';
str += 'World';
str; // 'Hello World'
```

🛑 If the left hand side of the `+` operator is a string, JavaScript will coerce the right hand side to a string. That means it is safe to concatenate objects, numbers, null, and undefined.

```javascripts
let str = 'Values: ';
str += 42;
str += ' ';

str += {};
str += ' ';

str += null;

str; // 'Values: 42 [object Object] null'
```

<b> `[Array].join()` </b>

🚀 The`[Array].join()` function creates a new string from concatenating all elements in an array. For example:

```js
['Hello', ' ', 'World'].join(''); // 'Hello World'
```
🚀 The first parameter to join() is called the separator. By default, the separator is a single comma `','`.

```js
['a', 'b', 'c'].join(); // 'a,b,c'
```
🚀 You can pass in any separator you want. Separators make `[Array].join()` the preferred choice for concatenating strings if you find yourself repeating the same character over and over again. For example, you can use `' ' `as the separator to join an array of words:


```js
// 'This happened  the night before Christmas'
['This' 'happened', 'the', 'night', 'before', 'Christmas'].join(' ');
```
- Or you can use` '/'` to join together URL fragments:

```js
// 'study.js/fundamentals/string-concat'
['study.js',  'fundamentals', 'string-concat'].join('/');
```
🚀 Separators make `Array.join() `a very flexible way to concatenate strings. If you want to join together a variable number of strings, you should generally use` join()` rather than a `for loop` with` +`.

<b> `String.concat()`</b>

JavaScript strings have a built-in `concat()` method. The `concat()`function takes one or more parameters, and returns the modified string. Strings in JavaScript are `immutable`, so `concat()` doesn't modify the string in place.

```js
const str1 = 'Hello';
const str2 = str1.concat(' ', 'World');

// 'Hello'. Strings are immutable, so `concat()` does not modify `str1`
str1;
// 'Hello World'
str2;
```
The `concat()` function is rarely used because it has more error cases than the + operator. For example, you would get unexpected behavior if you call concat() on a value that happens to be an array. You should use + instead of concat() unless you have a very good reason.

If you must use `concat()`, it is usually best to call it on an empty string:

```js
''.concat('Hello', ' ', 'World');
```

```js
"The car" + "is fast";
// output: "The caris fast"
```
Concatenation joins the strings end to end, combining them and outputting a brand new string value. If we would like to have a space between the words `car` and `fast`, we would need to include a `whitespace character` in one of the strings:
```js
"The car " + "is fast";
// output: "The car is fast"
```
🛑 <b>Remember </b>: We join strings and variables containing string values with concatenation.

```js
const book = "The Lost Symbol";
const author = "Dan Brown";

const favBook = "My favorite book is " + book + " by " + author + ".";

// output: My favourite book is The lost Symbol by Dan Brown.
```
🛑 When combining two or more strings through concatenation we are creating a new string that we can use throughout our program.

<b>Variables in Strings with Template Literals</b>

🛑 One special feature of the template literal feature is the ability to include expressions and variables within a string. Instead of having to use concatenation, we can use the `${}` syntax to insert a variable.

```js
const book = "The Lost Symbol";
const author = "Dan Brown";

const favBook = `My favorite book is ${book} by ${author}.`;

```
Including expressions in template literals is another way to accomplish the same result. 

<b>Instance methods are methods that are run on a string type.</b>

- A string offers a few unique methods you can use:


- `charAt(i)`
- `charCodeAt(i)`
- `codePointAt(i)`
- `concat(str)`
- `endsWith(str)`
- `includes(str)`
- `indexOf(str)`
- `lastIndexOf(str)`
- `localeCompare()`
- `match(regex)`
- `normalize()`
- `padEnd()`
- `padStart()`
- `repeat()`
- `replace(str1, str2)`
- `search(str)`
- `slice(begin, end)`
- `split(separator)`
- `startsWith(str)`
- `substring()`
- `toLocaleLowerCase()`
- `toLocaleUpperCase()`
- `toLowerCase()`
- `toString()`
- `toUpperCase()`
- `trim()`
- `trimEnd()`
- `trimStart()`
- `valueOf()`