JavaScript Strings are too vital
Tags: javascript, webdev, programming, beginners
Published: 2021-10-18 17:45:52

Strings as we know is a JavaScript data type. We use them to hold data that can be represented in text form. This data can be any sequence of characters.

For example, the username of a new user on Twitter can (& should) be wrapped inside a string.

It is very important for you as a JavaScript developer to understand what strings are, and how to manipulate them, because strings are just everywhere, in arrays, objects, functions, classes.

It's one of the data types you will always use.

## How do we use strings

Am going to use the CRUD (Create, Read/Access, Update, Delete) style to analyze this.

### Creating Strings

Strings in JavaScript can be created as string literals (primitives) or as string objects.

String literals are the common way to create strings, it is the primitive way.

String literals are created using single quotes (`''`), or double quotes (`""`), or backticks (`` ` ` ``).

```js
let username = 'john_doe';
```

Single quotes and double quotes are related, so we can change the example above to

```js
let username = 'john_doe';
```

It's just a matter of preference, but it is also recommended to stick with one in all your strings. So don't use single quotes for username and then use double quotes for the last name. Just stick with one.

And if you do stick with one, let's say single quotes, there may be times where your text has a single quote in it. You may have tried it, but it's not going to work because JavaScript is confused.

You can't use the same quote as the surrounding quote inside a string. I.e

```js
let error = 'john's wife'; // will return a syntax error
```

There are two ways of solving this

- Escape it: you can use `\` (an escape character) to escape the quote inside the string. We use it immediately before the inner quote i.e

```js
let msg = 'john\'s wife'; // will return john's wife
```

- Use a different quote: this is the default of most JavaScript formatters (like Prettier), they simply use a different quote as the surrounding quote like this

```js
let msg = "john's wife"; // will return john's wife
```

**Template literals**

We use backticks when we want to add some JavaScript expressions to a string.

```js
let age = `${currentYear - birthYear} years old`;
```

We call the expression above a template literal. JavaScript will convert the value of evaluating `currentYear - birthYear` to a string.

Take note of the dollar sign and curly braces as it is used to wrap the expression inside the template literal.

Without the backticks, age would simply be `${currentYear - birthYear} years old`.

All of the examples above are primitives, they are immutable, they cannot be altered, but they can be reassigned. We will see more about this later

String objects are created with the `new` keyword and the `String()` object.

```js
let username = new String('john_doe'); // typeof username = object
```

### Reading/Accessing Strings

In JavaScript, we can access a string's character using

- .charAt(): a method that takes in a position as a parameter and returns the character in that position.

```js
let username = 'john_doe';
username.charAt(1); // will return o (the first o)
```

By default, the string above is primitive and primitive strings don't have any properties or methods. So JavaScript converts a primitive string to a string object, and with that, we can use the properties and methods of string objects.

How does the `.charAt()` method really work?

If you `console.log(new String('john_doe'))`, the value returned is an object with keys as numbers (zero-based, index). Each of these keys is assigned a value from our username (john_doe) respectively not randomly.

So we can reproduce the `charAt()` function like this

```js
function charAt(object, position) {
  return object[position]; // custom way of accessing special keys in objects
}

let username = new String('john_doe');
console.log(charAt(username, 1)); // returns o (the first o)
```

This would bring us to the next one called

- bracket notation: we have seen this already in the `charAt()` function. This is the easiest way to access a character in a string.

```js
let username = 'john_doe';
username[1]; // will return o
```

What we see JavaScript giving us here, is the second element (item, character) in the string, just like in arrays, but what JavaScript is actually returning is the property called 1. Do you remember our string objects?

We could have said `username.1` which is common in objects, but that will return a syntax error, so a common way of solving this is using bracket notation. Here is an example

```js
let newUser = { username: 'john_doe', proUser: true };
```

Let's say I wanna access `proUser`, without knowing the property name; that is me accessing this array is going to depend on another variable and that I have no idea of its value

```js
let propertyName = 'proUser'; // pretend i never declared this
```

How would you access the object with the variable, you are surely not going to use `newUser.propertyName` that will just be `undefined`. The solution is bracket notation

```js
newUser[propertyName]; // as simple as ABC
```

**Loop a String**
We can loop through a string to access its characters.

```js
let username = 'john_doe';

for (let i = 0; i < username.length; i++) {
  console.log(username[i]);
}
```

We can use the for/in loop as well because remember it's an object behind the hood.

Tip: `username.length` is a property to check the number of characters in a string.

### Updating Strings

Strings cannot be updated, but we can reassign them.

```js
let username = 'john_doe';
username.replace('j', 'h');
console.log(username); // john_doe
```

But

```js
let username = 'john_doe';
username = username.replace('j', 'h');
console.log(username); // hohn_doe
```

Tip: `.replace()` is a method that replaces the first match of a character or characters in a string. The first parameter is usually replaced by the second.

### Deleting strings

Strings cannot be mutated, which means you cannot completely delete a declared and assigned string. You could reassign it a value of undefined or null but that is usually not recommended.

Trust me, you would hardly need to completely delete a string, most times where you'd want to delete a string is in an array or an object, which is possible.

That being said, you can remove texts or parts of a string from a string. But we will see this next.

## String methods

JavaScript strings have a lot of methods we can use to manipulate strings. Let's see the ones you will often use

### .charAt()

We've seen this before. It returns the character at a specified position

### .replace()

Again, we've seen this before. We use this to replace a character or characters with new ones. Let' see another example

```js
let msg = 'I will see Drake tomorrow';
msg = msg.replace('Drake', 'Kevin Hart');
console.log(msg); // I will see Kevin Hart tomorrow
```

### .indexOf()

This will return the position of the first found occurrence of a specified value in a string.

```js
let msg = 'john_doe';
console.log(msg.indexOf('o')); // 1
```

This method will return -1 if that value or character is not found.

### .lastIndexOf()

Just like `indexOf()`, the only difference is that this will return the last. So it's definitely going to go through all the characters in that string. (that's so stressful)

```js
let msg = 'john_doe';
console.log(msg.lastIndexOf('o')); // 6
```

If a character is not found, it returns -1.

### .substr(), .substring() & .slice()

They all do the same job; slicing out a part of a string, but in different ways

- `.slice()`: takes two params; start and end. Slices a string from the specified start position (inclusive) to the specified end position (not inclusive). It returns the sliced out string

```js
let msg = 'I will see Drake tomorrow';
console.log(msg.slice(11, 16)); // Drake
```

The `slice()` method supports negative values as parameters. This will make it start counting from the end.

```js
let msg = 'I will see Drake tomorrow';
console.log(msg.slice(-14, -9)); // Drake
```

- `.substring()`: takes two params, start, and end. Slices a string from the specified start position (inclusive) to the specified end position (not inclusive). It returns the sliced-out string.

```js
let msg = 'I will see Drake tomorrow';
console.log(msg.substring(11, 16)); // Drake
```

As you can see it is the twin sister of `slice()`. There's a difference though, `substring()` doesn't support negative values.

- `substr()`: takes two params, start, and length. Slices a string from the specified start position (inclusive) to the number of characters you wish to slice out (starting from the start position).

Now slicing Drake out dynamically will be a lot easier

```js
let username = 'Drake';
let msg = 'I will see Drake tomorrow';
console.log(msg.substr(msg.indexOf(username), username.length)); // Drake
```

It also supports negative values.

### .split() && .trim()

We use the `split()` method to split a string into an array. It takes a string as a parameter for splitting the string.

So if we had a list of fruits as a string, we can split it into an array like this

```js
let listOfFruits = 'Banana, Apple, Orange'
let fruitsArr = listOfFruits.split(',') // ['Banana', ' Apple', ' Orange']
```

To get rid of those whitespaces or any other whitespaces in a string we use the `trim()` method. So let's refactor the code above

```js
fruitsArr = fruitsArr.map((fruit) => {
  return fruit.trim();
})
console.log(fruitsArr) // ['Banana', 'Apple', 'Orange']
```

### .toUpperCase() && .toLowerCase()
JavaScript offers a method for converting a string to an upper case or to a lower case using `.toUpperCase()` and `.toLowerCase()` respectively.

```js
let username = 'john_doe'
console.log(username.substr(0,1).toUpperCase()+username.substr(1)) // John_doe
```

### .toString()
This method is used to convert to a string. We can convert a number for example to a string using this method

```js
let age = 30;
age = age.toString()
console.log(typeof age) // string
```

There are more methods in JavaScript strings that are very common like `.match(), .search()` but that would hopefully be a topic for another day. But in the meantime, you can check them out on MDN.

### Conclusion
Strings are very vital, it's something you will always use in any language at all. Knowing how it works will help you save a lot of time while coding.

Ok, that's it for today. Leave a comment for me if you wanna "holla" or correct something. You can follow me on Twitter [@elijahtrillionz](https://www.twitter.com/elijahtrillionz). I tweet useful content daily for you.
See ya!